Reputation: 1329
I have to classes :
template <class T>
class shared_vector
{
T data;
}
template <class T>
class device_vector
{
T data;
}
I want to write a function f which accects any kind of object, be it of type shared_vector
or device_vector
and sets some flags accordingly.
Now the obvious solution is to go for function overloading. But suppose the function f takes 10 arguments which can either be of shared_vector
or device_vector
,
I would have to write 1024 overloaded functions.
Another solution is to use a parent class hybrid_vector
from which both the device_vector
and shared_vector
inherit from.
But unfortunately, device_vector code is not in my control.
How should i solve this problem ?
NOTE : I know typeid (variable).name () can tell the type, but what will be my function declaration and how can I infer type from it ?
Upvotes: 0
Views: 72
Reputation: 179799
It might be an option to accept boost::variant<shared_vector<T>, device_vector<T>>
.
Another option is std::enable_if
:
template<typename V>
std:enable_if<
std::same_type<V, shared_vector<decltype(V::data)>::value |
std::same_type<V, device_vector<decltype(V::data)>::value ,
void>::type
foo(V const& vector);
Still going to be verbose if you have V1..V10
but it's just 2*10 checks, not 1024. And of course you can write your own is_device_or_shared<Vector>::value
to wrap those 2 tests in something slightly more readable.
Upvotes: 2