Calling different functions depending on the template parameter c++
I want to have something like that
class A
{
public:
Array& operator()()
{ . . . }
};
class开发者_JS百科 B
{
public:
Element& operator[](int i)
{ ... }
};
template<class T>
class execute
{
public:
output_type = operator()(T& t)
{
if(T == A)
Array out = T()();
else
{
Array res;
for(int i=0 ; i < length; ++i)
a[i] = t[i];
}
}
};
There are two issues here:
- meta-function replacing if-else in the execute operator()
- return type of execute operator()
Just specialize the template class.
template<class T>
class execute
{};
template<>
class execute<A>
{
A operator()(A& t)
{
/* use A, return A */
}
};
template<>
class execute<B>
{
B operator()(B& t)
{
/* use B, return B */
}
};
Just overload the operator:
// used for As
Array operator()(A& a)
{
// ...
}
// used for everything else
typename T::Element operator()(T& t)
{
// ...
}
If you just need A
and B
, the second could also be specific to B
:
// used for Bs
B::Element operator()(B& b)
{
// ...
}
精彩评论