c++ partial specialization: How can I specialize t

2019-02-25 03:37发布

#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'.

2条回答
三岁会撩人
2楼-- · 2019-02-25 04:03

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;
}
查看更多
Viruses.
3楼-- · 2019-02-25 04:06

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

template <class T1, typename T2 = void>
class A {
public:
    void taunt() { cout << "A"; }
};
查看更多
登录 后发表回答