c++ partial specialization: How can I specialize this template<class T1, class T2> to this template<class T1>?

跟風遠走 提交于 2019-12-04 04:30:00

问题


#include <iostream>
using namespace std;

template <class T1, class T2>
class A {
public:
    void taunt() { cout << "A"; }
};

template <class T1>
class A<T1, T1> {
public:
    void taunt() { cout << "B"; }
};

class B {};

class C {};

int main (int argc, char * const argv[]) {

    A<B> a;

    return 0;
}

How can I convert my two parameter template to a one parameter template?

The above code will give a compiler error on 'A a;' for 'wrong number of template arguments'.


回答1:


Template specialization can't be used to reduce the number of template arguments, to do that you should use defaults for some of the arguments.

So in order to allow usage of only one argument, and make that usage hit your specialization, you need a default for the second argument, which is the same as the first argument:

#include <iostream>
using namespace std;

template <class T1, class T2=T1>
class A {
public:
    void taunt() { cout << "A"; }
};

template <class T1>
class A<T1, T1> {
public:
    void taunt() { cout << "B"; }
};

class B {};

class C {};

int main (int argc, char * const argv[]) {

    A<B> a;
    a.taunt(); // Prints "B"

    return 0;
}



回答2:


You can use a (sensible) default for the second instantiating type:

template <class T1, typename T2 = void>
class A {
public:
    void taunt() { cout << "A"; }
};


来源:https://stackoverflow.com/questions/10253219/c-partial-specialization-how-can-i-specialize-this-templateclass-t1-class-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!