C++ 函数模板参数推导
我已经为我当前的问题创建了一个示例。 我希望能够在不指定模板类型的情况下调用以下函数,因为编译器应该能够找到类型:C++ 函数模板参数推导,c++,templates,std-function,C++,Templates,Std Function,我已经为我当前的问题创建了一个示例。 我希望能够在不指定模板类型的情况下调用以下函数,因为编译器应该能够找到类型: template<typename T, class Iterable> void foreach1(std::function<void(T&)> action, Iterable& iterable) { std::cout << typeid(T).name() << std::endl; for
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);
}
模板
void foreach1(标准::函数动作,可编辑和可编辑){
将参数传递给类型依赖于推断模板参数的参数时,不允许进行std::cout隐式转换
我建议使用第二种选择:
template<class Action, class Iterable>
void foreach2(Action action, Iterable& iterable)
然后编写一个模板以获取std::function
的参数类型:
std::function(action)
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;
模板结构std_func_param{};
模板结构std_func_param{using type=T;};
使用std_func_param_t=typename std_func_param::type的模板;
像这样使用它:
using T = std_func_param_t<decltype(std::function(action))>;
使用T=std\u func\u param\T;
这是否回答了您的问题?将lambda转换为std::function会有运行时成本吗?我在一些地方读到,在大多数情况下不使用std::function。这是您必须使用它的一种情况吗?@Dolfos可能会有运行时成本,但在这种情况下,std::function(action)
仅在decltype()中使用
,这意味着未对其进行评估。未构造实际的std::function
。如果未对其进行评估,为什么会有运行时成本?@Dolfos我的意思是,如果std::function(action),可能会有运行时成本
已计算。由于没有,因此没有额外的成本。编译器是否会优化std::function的构造,因为decltype()不算作“使用”变量?
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))>;