假设我有以下定义:
int f(int ) { return 1; } // a)
template<typename T> int f(T x) { return 2; } // b)
Run Code Online (Sandbox Code Playgroud)
我明白,如果我打电话f,例如f(1),非模板重载a)将是首选,但是有没有办法明确地引用a)?例如,我可以用来f<int>明确地参考b).
作为为什么这会有用的一个例子,请考虑以下函数:
template<typename Func, typename T> void print_result(Func f, T arg)
{
std::cout << f(arg) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试使用它f,例如,print_result(f,1)我得到一个编译错误(编译器不知道f我的意思).我可以用print_result(f<int>,1)它来告诉它使用b),但是如何告诉它使用a)?
我发现我可以使用print_result(static_cast<int (*)(int)>(f), 1),但这感觉很乱,而且很麻烦.有没有更好的办法?
使用模板专业化:
template<>
int f<int>(int x ) { return 1; } // a)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
183 次 |
| 最近记录: |