【发布时间】:2015-03-21 12:55:44
【问题描述】:
我正在寻找一种使用自定义成员方法扩展 C++ 类的方法。就像 C# 对 Linq 扩展所做的那样:
public static class Factory
{
public static int getIndex(this List<int> source, int value)
{
int index = 0;
foreach (int item in source)
{
if (item == value)
return index;
index++;
}
return -1;
}
}
此 C# 代码将为列表的每个实例添加一个方法。所以你可以写:
List<int> myList = new List<int>();
myList.Add(26);
myList.Add(42);
myList.Add(37);
myList.Add(3);
int index = myList.getIndex(42);
这在 C++ 中也有可能吗?如何正确地将这样的方法添加到 std::vector<T> 无需子类化?
抱歉,如果这是重复的,如果不使用继承,我找不到任何回答我的问题的东西。
【问题讨论】: