I’m writing a template for which I’m trying to provide a specialization on a class which itself is a template class. When using it I’m actually instanciating it with derivitives of the templated class, so I have something like this:
template<typename T> struct Arg
{
static inline const size_t Size(const T* arg) { return sizeof(T); }
static inline const T* Ptr (const T* arg) { return arg; }
};
template<typename T> struct Arg<Wrap<T> >
{
static inline const size_t Size(const Wrap<T>* arg) { return sizeof(T); }
static inline const T* Ptr (const Wrap<T>* arg) { return arg.Raw(); }
};
class IntArg: public Wrap<int>
{
//some code
}
class FloatArg: public Wrap<float>
{
//some code
}
template<typename T>
void UseArg(T argument)
{
SetValues(Arg<T>::Size(argument), Arg<T>::Ptr(&argument));
}
UseArg(5);
UseArg(IntArg());
UseArg(FloatArg());
In all cases the first version is called. So basically my question is: Where did I went wrong and how do I make him call the the version which returns arg when calling UseArg(5), but the other one when calling UseArg(intArg)? Other ways to do something like this (without changing the interface of UseArg) are of course welcome to.
As a note the example is a little simplyified meaning that in the actual code I’m wrapping some more complex things and the derived class has some actual operations.
I think there are three approaches:
1) Specialize Arg for derived types:
This sucks, because you can’t know in advance what types you will have. Of course you you can specialize once you have these types, but this has to be done by someone who implements these types.
2) Do not provide default one and specialize for basic types
It’s not ideal too (depends on how many “basic types” you expect to use)
3) Use IsDerivedFrom trick
Calling test() outputs (as I understand that’s your goal):
Extending it to work with more types like Wrap is possible, but messy too, but it does the trick – you don’t need to do a bunch of specializations.
One thing worth mentioning is that in my code
ArgDerivedis specialized withIntArginstead ofWrap<int>, so callingsizeof(T)inArgDerived<T, true>returns size ofIntArginstead ofWrap<int>, but you can change it tosizeof(Wrap<T::type>)if that was your intention.