Rab*_*bah 8 c++ templates class
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)
Run Code Online (Sandbox Code Playgroud)
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.
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?
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.
Just to illustrate what I mean:
template <class T>
class Compute
{
public:
T Function_B(T parameter)
{
return f.eval(parameter);
}
private:
SomeClass<T> f;
}
Run Code Online (Sandbox Code Playgroud)
And a class:
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
}
Run Code Online (Sandbox Code Playgroud)
Que*_*tin 10
怎么样(未经测试):
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;
};
Run Code Online (Sandbox Code Playgroud)
注意:如果您喜欢它添加的第一个/第二个语义,则其std::pair工作原理与std::tuple此处完全相同。
另外,请注意这T(SomeParameter)是C样式的强制转换,如果T不是类类型,则可能会出现问题。考虑T{}或static_cast<T>()。
| 归档时间: |
|
| 查看次数: |
495 次 |
| 最近记录: |