我正在研究模板特化,但无法理解混合类和 int。
以下代码编译失败click to compile .有人可以在这里建议正确的方法。我想专攻 int 类。第二个模板 m 应定义为 0,但如何指定。
#include <iostream>
using namespace std;
template <class T,int m>
void fun(T a )
{
cout << "The main template fun(): " << a << " " << m << endl;
}
template<>
void fun(int a)
{
cout << "Specialized Template for int type: " << a << endl;
}
int main()
{
fun<char,10>('a');
fun<int,20>(10);
fun<float,12>(10.14);
}
错误是:
prog.cpp:11:6: error: template-id 'fun<>' for 'void fun(int)' does not match any template declaration
void fun(int a)
^
最佳答案
我建议改变参数的顺序来推导 T,然后简单地使用重载:
template <int m, class T>
void fun(T a )
{
cout << "The main template fun(): " << a << " " << m << endl;
}
template <int m>
void fun(int a)
{
cout << "Template for int type: " << a << endl;
}
使用方法:
fun<10>('a');
fun<20>(10);
fun<12, float>(10.14); // or simply fun<12>(10.14f);
关于c++ - 混合类和 int 的函数模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45521030/