【发布时间】:2020-01-14 23:13:22
【问题描述】:
我已经创建了一个我当前问题的示例。 我希望能够在不指定模板类型的情况下调用以下函数,因为编译器应该能够找出类型:
template<typename T, class Iterable>
void foreach1(std::function<void(T&)> action, Iterable& iterable) {
std::cout << typeid(T).name() << std::endl;
for (auto& data : iterable)
action(data);
}
如果我这样调用函数:
std::vector<int> a = { 1, 2, 3 };
foreach1([](int& data) {
std::cout << data << std::endl;
}, a);
我得到一个错误。我知道我可以通过以下方式用模板替换 std::function 来解决问题:
template<class Action, class Iterable>
void foreach2(Action action, Iterable& iterable) {
//std::cout << typeid(T).name() << std::endl; // no access to T
for (auto& data : iterable)
action(data);
}
但是这样做我失去了对 T 类型的访问权限。 有没有办法保持对类型 T 的访问并能够使用模板参数推导?
【问题讨论】:
标签: c++ templates std-function