Template constructor in a class template - how to explicitly specify template argument for the 2nd parameter?

后端 未结 3 797
借酒劲吻你
借酒劲吻你 2020-12-03 15:26

Template constructor in a class template - how to explicitly specify template argument for the 2nd parameter?

compile error when tried to explicit specify template

3条回答
  •  佛祖请我去吃肉
    2020-12-03 15:48

    Fixing your code, the following would work:

    template class TestTemplate {
    public:
        //constructor 1
        template TestTemplate(Y * p) {
            cout << "c1" << endl;
        }
    
        //constructor 2
        template TestTemplate(Y * p, D d) {
            cout << "c2" << endl;
        }
    
        template
        void foo(A a, B b) {
            cout << "foo" << endl;
        }
    };
    
    int main() {
        TestTemplate tp(new int());
    
        tp.foo(new int(), "hello");
    
        TestTemplate tp2(new int(),2);
    }
    

    You cannot use T for the class template parameter and the constructor template parameter. But, to answer your question, from [14.5.2p5]:

    Because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function templates.

    Therefore, you cannot explicitly specify template arguments for constructor.

提交回复
热议问题