c++ - 混合类和 int 的函数模板特化

标签 c++ templates template-specialization

我正在研究模板特化,但无法理解混合类和 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/

相关文章:

c++ - && 对 lambda 表达式有什么好处?

c++ - 仅在类范围内的模板特化

c++ - 线程数组并试图将多个参数传递给函数不起作用?

java - JVM 在哪里以及为什么检查入口方法 main(String args[]) 的返回类型是否为 void 而不是其他任何东西?

c++ - 在 std::u8string 和 std::string 之间转换

带 float 的 C++ 模板特化

c++:用户定义类型的 vector ?

C++ 函数模板特化

c++ - 如果使用默认模板,如何产生编译器错误?

c++ - 在 Cygwin 中编译 : 'EOF' was not declared in this scope, 在 CentOS 中编译正常