C++允许非类型模板参数为整数或枚举类型(包括布尔和字符的整数),以及指向任意类型的指针和引用.
我已经看到广泛使用的整数,布尔和枚举参数,我很欣赏它们的实用性.我甚至已经看到巧妙地使用字符参数进行字符串的编译时解析.
但我想知道什么是非类型模板参数的一些用例,它们是指针或对任意类型的引用?
在此示例中,函数被传递给隐式实例化的函数模板.
// Function that will be passed as argument
int foo() { return 0; }
// Function template to call passed function
template<typename F>
int call(F f) {
return f();
}
template<typename F, typename A>
int call(F f, A a) {
return f(a);
}
int a = call(foo);
Run Code Online (Sandbox Code Playgroud)
我们可以通过添加重载来破坏此代码foo().
int foo(int i) { return 0; }
Run Code Online (Sandbox Code Playgroud)
名称" foo"现在不明确,示例将不再编译.这可以通过显式提供函数指针类型信息来进行编译.
int (*func_takes_void)() = foo;
int a = call(func_takes_void);
int (*func_takes_int)(int) = foo;
int b = call(func_takes_int, 0);
Run Code Online (Sandbox Code Playgroud)
http://coliru.stacked-crooked.com/a/e08caf6a0ac1e6b9
是否可以推断出函数指针类型?如果是这样,为什么我的尝试下面不起作用,这是正确的方法? …