如果类也是模板,是否可以使用模板参数调用构造函数?
#include <stdio.h>
#include <iostream>
template <class A>
struct Class
{
template <class B>
Class(B arg) { std::cout << arg << std::endl; }
};
int main()
{
Class<int> c<float>(1.0f);
Class<int>* ptr = new Class<int><float>(2.0f);
return 0;
}
编辑:所以我想调用特定模板构造函数的唯一方法是使用casted paramterers将它调用到你想要的模板类型:
#include <stdio.h>
#include <iostream>
template <class A>
struct Class
{
template <class B>
Class(B arg) { std::cout << arg << std::endl; }
Class(double arg) { std::cout << "double" << std::endl; }
Class(float arg) { std::cout << "float" << std::endl; }
};
int main()
{
Class<int> c(1.0f);
Class<int>* ptr = new Class<int>((double)2.0f);
return 0;
}
//这个输出: 浮动 双
edit2:但是构造函数参数本身不属于构造函数模板参数会发生什么?
template <class B, class C>
Class(B arg) { /* how do you specify ?? C */ }
答案 0 :(得分:4)
在您给出的示例中,实际上不需要显式地赋予template
参数来调用构造函数,如:
Class<int> c<float>(1.0f);
简单地将参数提供为1.0f
就足够了:
Class<int> c(1.0f);
同样适用于new
示例。话虽如此,我认为构造函数不能使用template
参数显式调用(与普通函数不同)。
答案 1 :(得分:2)
edit2:但是构造函数参数本身不属于构造函数模板参数会发生什么?
然后你可以传入一个已经编码的参数
template<typename T> struct encodeType { };
struct A {
template<typename T, typename U>
A(T t, encodeType<U>) { }
};
A a(1, encodeType<float>());
答案 2 :(得分:1)
Class<int> c(1.0f); //f in 1.0 makes it float type!
Class<int>* ptr = new Class<int>(2.0f);
这就够了。它将调用具有模板参数float
的构造函数。从参数1.0f
开始,编译器将推导出构造函数模板的类型参数。由于1.0f
是float
,因此编译器将推导出的类型参数为float
。
同样请看这些:
Class<int> c(1.0); //this will invoke Class<int><double>(double);
Class<int>* ptr = new Class<int>(2); //this will invoke Class<int><int>(int);
答案 3 :(得分:1)
您需要明确说明与类本身一致的模板类型(在您的示例中为A
)。但是你不需要说出B
是什么类型。编译器知道您1.0f
传递B == float
。构造函数调用中没有任何内容可以帮助编译器找出A
是什么,所以你必须告诉它:
Class<int> c(1.0f);
Class<int>* ptr = new Class<int>(2.0f);