問題描述
類模板中的模板構造函數 - 如何為第二個參數顯式指定模板參數?
Template constructor in a class template - how to explicitly specify template argument for the 2nd parameter?
嘗試為構造函數 2 顯式指定模板參數時出現編譯錯誤.如果我真的想顯式調用構造函數 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 ?
請注意,當您要明確指定刪除器類型時,這與 boost::shared_ptr 的情況相同.
Please note this is the same situation for boost::shared_ptr when you want to explicitly specify the deleter type.
注意對于非-構造函數foo(),明確指定工作正常.
N.B. For non-construction function foo(), explicitly specify works fine.
N.B 我知道它工作正常沒有為構造函數 2 明確指定第二個作為模板參數推導通常工作正常,我只是好奇如何明確指定它.
N.B I know it works fine without specify the 2nd one explicitly for the constructor 2 as template argument deduction normally just works fine, I am just curious how to specify it explicitly.
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;
}
推薦答案
修復您的代碼,以下內容將起作用:
Fixing your code, the following would work:
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);
}
您不能將 T
用于類模板參數 和 構造函數模板參數.但是,要回答您的問題,來自 [14.5.2p5]:
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.
這篇關于類模板中的模板構造函數 - 如何為第二個參數顯式指定模板參數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!