I have the following code in C++ -
(我在C ++中有以下代码-)
template <class T>
class TempClass {
T value;
public:
TempClass(T item)
{
value = item;
}
T getValue()
{
return value;
}
};
int main()
{
TempClass<string>* String =
new TempClass<string>("Rin>Sakura");
cout << "Output Values: " << String->getValue()
<< "
";
class TempClass<int>* integer = new TempClass<int>(9);
cout << "Output Values: " << integer->getValue();
}
What I would like to do is use multiple templates with the above class TempClass.
(我想做的是在上述类TempClass中使用多个模板。)
I know one way of doing this is by using (我知道一种方法是使用)
template <class T1, class T2>
, but if I do that then all instances of the class must have 2 template arguments.
(,但是如果我这样做,则该类的所有实例都必须具有2个模板参数。)
What I want to do is something more like : (我想做的更像是:)
if (flag)
//initialize an instance of TempClass with one template
TempClass<string> s("haha");
else
//initialize an instance of TempClass with 2 templates.
TempClass<string, int> s("haha", 5);
Is there a way to do this without using another new class?
(有没有不用另一个新类就可以做到这一点的方法?)
ask by Rijul Ganguly translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…