假设我有一个名为的类模板Compute
,和另一个名为Function_A
使用成员函数模板:
template <typename T> void Evaluate(T parameter)
我被迫使用该类Function_A
就这样。我已经知道了T
只能是两种类型之一type_1
and type_2
.
有没有办法有类似的东西Compute<T> C
作为成员变量Function_A
而不是定义本地Compute<T>
里面有物体Evaluate(...)
?我知道这违背了使用模板的理念,因此它可能是不可能的,但在这种情况下理想情况下可以代替吗?
我尝试有两个成员Compute<type_1> C1
and Compute<type_2> C2
in Function_A
,然后在if (typeid(T) == typeid(type_1))
但这是相当可怕的,并且也违背了使用模板的理念。
只是为了说明我的意思:
template <class T>
class Compute
{
public:
T Function_B(T parameter)
{
return f.eval(parameter);
}
private:
SomeClass<T> f;
}
还有一个类:
class Function_A
{
public:
template <typename T> T Evaluate(T parameter)
{
Compute<T> C; //this is very expensive!
T value = C.Function_B(parameter);
return value;
}
private:
double SomeParameter;
//Compute<T> C; //conceptually what I want
}
怎么样(未经测试):
class Function_A
{
public:
template <typename T> void Evaluate(T parameter)
{
T value = std::get<Compute<T>>(computers).Function_B(parameter);
return T(SomeParameter) * value;
}
private:
double SomeParameter;
std::tuple<Compute<type_1>, Compute<type_2>> computers;
};
Note: std::pair
的工作原理与std::tuple
在这里,如果您喜欢它添加的第一/第二语义。
另外,请注意T(SomeParameter)
是 C 风格的强制转换,如果T
不是一个类类型。考虑T{}
or static_cast<T>()
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)