C#扩展方法类似物在C 中

C# extension methods analogue in C++

本文关键字:类似物 扩展 方法      更新时间:2023-10-16

c#具有此小功能:https://learn.microsoft.com/en-us/dotnet/csharp/csharp/programprampramming-guide/classes-andscents-andscents-shipss-shipsions/extension-methods

这真的很酷。让我举一个例子:

我想将concat方法添加到std::vector,但我不想继承它。此功能将非常有用。您是否有C 中的任何类似功能,可以在不继承原始类型的情况下将函数添加到类型中?我要提供语言级功能。

在C 中,这是不可能的;话虽这么说,您可以实现一个对std::vector作为第一个参数的函数,以相似的目的为扩展方法(或多或少只是句法糖)。

免费功能可能是您的朋友,例如

namespace VectorMethods
{
    std::string contat(const std::vector<std::string>& vec)
    {
        // return result of concatenating vector
    }
}