【问题标题】:function template specialization for mixed class and int混合类和 int 的函数模板特化
【发布时间】:2017-08-05 10:48:16
【问题描述】:

我正在学习模板专业化但无法理解混合类和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)
      ^

【问题讨论】:

  • 您不能随意对函数进行部分特化。

标签: c++ templates template-specialization


【解决方案1】:

我建议改变参数的顺序来推导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);

【讨论】:

    【解决方案2】:

    我假设您正在尝试做的是专门化模板,以便表单的任何调用

    fun<int, N>(...);
    

    调用专业化?

    这需要将fun() 部分特化为int,但C++ 语言禁止部分特化函数模板。但是,我们可以部分特化类模板就好了。因此,一种实现您想要的方法是使用函数对象实现您的 fun() 函数,如下所示:

    // General case
    template <typename T, int N>
    struct do_fun {
         void operator()(T a) {
            cout << "The main template fun(): " << a  << "  " << N << endl;  
         } 
    };
    
    // Specialisation for int
    template <int N>
    struct do_fun<int, N> {
        void operator()(int a) {
            cout << "Specialized Template for int type: " << a << endl;
        }
    };
    

    然后您可以提供一个使用函数对象的包装函数模板:

    template <typename T, int N>
    void fun(T a) {
        do_fun<T, N>{}(a);
    }
    

    Coliru example

    【讨论】:

      猜你喜欢
      • 2019-12-15
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      相关资源
      最近更新 更多