繁体   English   中英

std::function 模板参数推导

[英]std::function template argument deduction

我已经创建了一个示例我当前的问题。 我希望能够在不指定模板类型的情况下调用以下函数,因为编译器应该能够找出类型:

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类型的访问并能够使用模板参数推导?

将参数传递给类型依赖于推导模板参数的参数时,不允许进行隐式转换。

我建议使用第二个选项:

template<class Action, class Iterable>
void foreach2(Action action, Iterable& iterable)

并确定T ,开始制作std::function出来的action

std::function(action)

然后编写一个模板来获取std::function的参数类型:

template <typename T> struct std_func_param {};
template <typename R, typename T> struct std_func_param<std::function<R(T)>> {using type = T;};
template <typename T> using std_func_param_t = typename std_func_param<T>::type;

像这样使用它:

using T = std_func_param_t<decltype(std::function(action))>;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM