C++中的模板疑问

Rah*_*arg 7 c++ templates

#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所以第一个版本被调用.

  • 技术上正确,但你可以提到使用test <2>()会调用第二个,因为`2`解析为`int`. (2认同)

小智 9

尝试:

test<(int())>();
Run Code Online (Sandbox Code Playgroud)

  • @sbi没有它是一个很好的暗示,虽然错过了一些解释.`int()`周围的parens使它成为`int`类型的表达式. (4认同)
  • @Johannes:的确如此._I_应该在我脱口而出之前尝试过... @tyms:抱歉.我删除了我的投票.(但我不会投票,因为这并不能解释你为什么会这样做.) (2认同)

jco*_*der 5

我并不完全清楚你想要实现的目标.但是,如果您在使用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)

  • `+ 1`这里唯一的答案显示了如何做,IMO,Rahul实际上想做的事 - 定义一个专业化. (3认同)