类模板中的模板构造函数 - 如何为第二个参数显式指定模板参数?

Gob*_*0st 11 c++ templates

类模板中的模板构造函数 - 如何为第二个参数显式指定模板参数?

尝试显式指定构造函数2的模板参数时编译错误.如果我真的想要显式调用构造函数2,我应该怎么做?

请注意,当您想明确指定删除器类型时,boost :: shared_ptr的情况也是如此.

NB对于构造函数foo(),显式指定工作正常.

注意我知道它没有为构造函数2明确指定第二个,因为模板参数推导通常只是工作正常,我只是很好奇如何明确指定它.

template<class T> class TestTemplate {
public:
    //constructor 1
    template<class Y> TestTemplate(T * p) {
        cout << "c1" << endl;
    }

    //constructor 2
    template<class Y, class D> TestTemplate(Y * p, D d) {
        cout << "c2" << endl;
    }

    template<class T, class B>
    void foo(T a, B b) {
        cout << "foo" << endl;
    }
};

int main() {
    TestTemplate<int> tp(new int());//this one works ok call constructor 1
    //explicit template argument works ok
    tp.foo<int*, string>(new int(), "hello");

    TestTemplate<int> tp2(new int(),2);//this one works ok call constructor 2

    //compile error when tried to explicit specify template argument for constructor 2
    //How should I do it if I really want to explicit call constructor 2?
    //TestTemplate<int*, int> tp3(new int(), 2); //wrong
    //TestTemplate<int*> tp3<int*,int>(new int(), 2); //wrong again

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Jes*_*ood 24

修复你的代码,以下工作:

template<class T> class TestTemplate {
public:
    //constructor 1
    template<class Y> TestTemplate(Y * p) {
        cout << "c1" << endl;
    }

    //constructor 2
    template<class Y, class D> TestTemplate(Y * p, D d) {
        cout << "c2" << endl;
    }

    template<class A, class B>
    void foo(A a, B b) {
        cout << "foo" << endl;
    }
};

int main() {
    TestTemplate<int> tp(new int());

    tp.foo<int*, string>(new int(), "hello");

    TestTemplate<int> tp2(new int(),2);
}
Run Code Online (Sandbox Code Playgroud)

您不能使用T类模板参数构造函数模板参数.但是,从[14.5.2p5]回答你的问题:

因为显式模板参数列表遵循函数模板名称,并且因为在不使用函数名称的情况下调用转换成员函数模板和构造函数成员函数模板,所以无法为这些函数模板提供显式模板参数列表.

因此,您无法为构造函数显式指定模板参数.


Che*_*Alf 9

您无法显式指定构造函数的模板参数,因为构造函数本身没有名称,因此没有语法.

但是,您可以确保通过推断出正确的模板参数

  • 转换实际参数,和/或

  • 引入"人为的"额外参数,以便在必要时携带类型信息和/或

  • 使用工厂功能.

例如,您可以定义

template< class Type > struct TypeCarrier{ typedef Type T; };

struct MyClass
{
    template< class Type >
    MyClass( TypeCarrier< Type > ) { ... }
};

...
MyClass o( TypeCarrier<int>() );
Run Code Online (Sandbox Code Playgroud)

但是不要忘记这些技术.

相反,如果明显需要明确指定构造函数模板参数弹出,请考虑设计是否真的合理?

或许,如果你反省一下,这是你可以使用一些简单的设计