【发布时间】:2019-03-06 21:01:19
【问题描述】:
我正在尝试编写一个模板函数,该函数在某些结构集合中迭代用户指定的字段。比如我想写如下C++:
struct Example {
int a;
bool b;
};
template<std::function<Field& (Class)> GetField, typename Field, typename Class>
void myFunc(std::iterator<Class> begin, size_t const length) {
cout << length << endl;
for (size_t i{ 0 }; i < length; ++begin, ++i) {
Field const &field{ GetField(*begin) };
// Forward field to some other template function
anotherTemplateFunction<Field>(field);
}
}
void main() {
Example exArray[]{ {5, true}, {8, false} };
std::list<Example> exList{ exArray, exArray + _countof(exArray) }
// Examples of how I would like to call myFunc...
myFunc<Example::a>(exArray, _countof(exArray));
myFunc<Example::b>(exList.begin(), exList.size());
}
以上内容不起作用,但希望意图很明确。如何编写 myFunc 模板方法来完成对每个迭代项的某些字段的通用迭代?或者,如果有某种方式(在 Boost 或标准库中)可以直接在 exArray[i].a 上创建迭代器,那也是可以接受的。
【问题讨论】: