将模板函数作为普通函数的参数传递
Passing template function as argument for normal function
我想知道是否可以将模板函数(或其他函数)作为参数传递给第二个函数(不是模板)。向谷歌询问这一点似乎只提供了相反的信息(作为模板参数传递的函数)
我能找到的唯一相关页面是 http://www.beta.microsoft.com/VisualStudio/feedbackdetail/view/947754/compiler-error-on-passing-template-function-as-an-argument-to-a-function-with-ellipsis(不是很有帮助)
我期待这样的东西:
template<class N>void print(A input){cout << input;}
void execute(int input, template<class N>void func(N)){func(input)}
然后打电话
execute(1,print);
那么,可以这样做还是必须为 execute() 定义另一个模板?
函数模板表示无限重载集,因此除非您具有与专用化兼容的目标类型,否则函数类型的推导总是失败。例如:
template<class T> void f(T);
template<class T> void h(T);
void g() {
h(f); // error: couldn't infer template argument 'T'
h(f<int>); // OK, type is void (*)(int)
h<void(int)>(f); // OK, compatible specialization
}
从上面我们可以看到,程序的有效性要求我们为函数模板指定模板参数,而一般来说,指定它们并不总是直观的。您可以改为使用通用重载调用运算符将print
函子作为额外的间接级别:
struct print {
template<typename T>
void operator()(T&& x) const {
std::cout << x;
}
};
现在,您可以让execute
接受任何 Callable 并使用输入调用它:
template<class T, class Op>
void execute(T&& input, Op&& op) {
std::forward<Op>(op)(std::forward<T>(input));
}
void g() { execute(1, print{}); }
通用 lambda (C++14) 使它更加简洁:
execute(1, [] (auto&& x) { std::cout << x; });
执行需要是一个模板 - 编译器无法创建适用于任何输入类型的单个版本的 execute。 现在,如果您为此特定函数指定了 N 是什么 - 例如,如果您制作了第二个参数 print- 那么它应该是合法的。
相关文章:
- 如何在C++中将迭代器作为函数参数传递
- 为什么我不能将引用作为 std::async 的函数参数传递
- 节点插件 API 将数组作为函数参数传递
- 将字符串数组作为函数参数传递
- 如何通过 C++ 中的函数参数传递初始值设定项列表的固定大小的初始值设定项列表?
- 我可以动态创建新地图并作为函数参数传递吗?
- 将任意模板向量作为函数参数C++传递
- 将函数指针作为函数参数传递的目的
- C++:通过函数参数传递的值给出不同的结果
- 当数组大小在C++中未知时,如何在运行时将对字符串数组的引用作为函数参数传递?
- 通过宏将函数参数传递给函数
- C++:访问作为函数参数传递的双指针数组所指向的变量的值
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- 将派生类构造函数参数传递给受保护的成员
- 将指向数组的指针作为函数参数传递,这本身就是另一个函数的返回值?
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 有什么理由C++ 11+ std::mutex 应该声明为全局变量,而不是作为函数参数传递到 std::thread 中
- 如何将派生类作为函数参数传递:如果派生类成员不在父类中怎么办
- 如何将变量作为构造函数参数或函数参数传递
- 当数组对象以函数参数传递时,为什么复制构造函数会自称