#include <iostream>
using namespace std;
template<typename T> void test()
{
cout << "Called from template T";
}
template<int I> void test()
{
cout << "Called from int";
}
int main()
{
test<int()>();
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码片段中test<int()>()调用第一个版本并提供输出
Called from template T
为什么不调用第二个版本?
Pra*_*rav 11
根据ISO C++ 03(Section 14.3/2)
在模板参数中,a type-id和表达式之间的歧义被解析为a type-id. int()是一个type-id所以第一个版本被调用.
小智 9
尝试:
test<(int())>();
Run Code Online (Sandbox Code Playgroud)
我并不完全清楚你想要实现的目标.但是,如果您在使用int而不是任何其他类型实例化模板时想要使用不同的模板特化,那么这就是您需要的语法 -
#include <iostream>
using namespace std;
template<typename T> void test()
{
cout << "Called from template T";
}
template<> void test<int>()
{
cout << "Called from int";
}
int main()
{
test<int>();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
248 次 |
| 最近记录: |