有没有办法在非模板类中定义模板成员? [英] Is there a way to define a template member in a non-template class?
问题描述
说我有一个名为 Compute
的类模板,另一个名为 Function_A
的类具有成员函数模板:
Say I have a class template named Compute
, and another class named Function_A
with a member function template:
template <typename T> void Evaluate(T parameter)
我必须使用 Function_A
原样。我已经知道 T
只能是 type_1
和 type_2 $
I am constrained to use the class Function_A
as it is. I already know that T
can only be one of two types type_1
and type_2
.
是否有一种类似于 Compute< T>的方法? C
作为 Function_A
的成员变量,而不是定义本地 Compute< T>
对象内 Evaluate(...)
?我知道这与使用模板的原则背道而驰,因此这不可能,但在那种情况下可以做到吗?
Is there a way to have something similar to Compute<T> C
as a member variable of Function_A
instead of defining a local Compute<T>
object inside Evaluate(...)
? I know that this is against the philosophy of using templates, hence it is likely not possible, but can ideally be done in that case instead?
我尝试过拥有两个成员 Compute< type_1> C1
和 Compute< type_2>
,然后在 Function_A
中的C2 下使用它们,如果(typeid(T)== typeid(type_1))
,但这很荒谬,并且也反对使用模板的哲学。
I tried to have two members Compute<type_1> C1
and Compute<type_2> C2
in Function_A
, and then use them under an if (typeid(T) == typeid(type_1))
but it's a pretty hideous, and against the philosophy of using templates as well.
仅说明我的意思:
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;
};
注意: std :: pair
可以工作如果您喜欢它添加的第一个/第二个语义,则与 std :: tuple
完全相同。
Note: std::pair
would work exactly the same as std::tuple
here, if you fancy the first/second semantics it adds.
另外,请注意, T(SomeParameter)
是C样式的强制转换,如果 T
不是类,则可能会出现问题类型。考虑 T {}
或 static_cast< T>()
。
Additionally, note that T(SomeParameter)
is a C-style cast, which could be problematic if T
is not a class type. Consider T{}
or static_cast<T>()
.
这篇关于有没有办法在非模板类中定义模板成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!