c++ partial specialization: How can I specialize this template to this template?

后端 未结 2 1822
花落未央
花落未央 2021-01-20 06:59
#include 
using namespace std;

template 
class A {
public:
    void taunt() { cout << \"A\"; }
};

template 

        
2条回答
  •  猫巷女王i
    2021-01-20 07:52

    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 
    using namespace std;
    
    template 
    class A {
    public:
        void taunt() { cout << "A"; }
    };
    
    template 
    class A {
    public:
        void taunt() { cout << "B"; }
    };
    
    class B {};
    
    class C {};
    
    int main (int argc, char * const argv[]) {
    
        A a;
        a.taunt(); // Prints "B"
    
        return 0;
    }
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题