Domanda

I'd like to place a POD type constrain on type parameter T of class template A and then derive another class template B from the satisfactory A. Besides, B is supposed to have different implementation according to constancy of instance of A. The purpose of doing all this is about, well you know, for better type checking before runtime.

All I can figure out is a tentative definition of A

template <typename T, typename POD=void>
class A;
template <typename T>
class A <T, std::enable_if<std::is_pod<T>::value>::type>
{
    //blah...
};

so that A can't be instantialized when passing non-POD type, as you might have noticed that partial parameterization does the trick like a type switch.

But I can't figure out how B could be defined. I presume it looks like the following

template <typename A?>
class B;
template <>
B<const A?> : public A?
{
    //blah...
};
template <>
B<A?> : public A?
{
    //blah...
};

Any brilliant idea?

PS: Personally I tend to be highly critical. But just post how you think this could be done anyway.

È stato utile?

Soluzione

There is no brilliant idea if the specializations are going to be completely different. You have to go with this:

template <typename T>
class B;

template <typename T>
class B<const A<T>> : public A<T>
{

};

template <typename T>
class B<A<T>> : public A<T>
{

};

which is almost same as you've written yourself except ? symbol.

You can instantiate this class as:

B<A<int>>       x; //it chooses the second specialization
B<const A<int>> y; //it chooses the first specialization

See online demo. Note that you've forgotten typename here:

typename std::enable_if<std::is_pod<T>::value>::type

I fixed that too.

If some code in the specializations are going to be same, then you could do some trick in order to share the common part, but I cannot suggest anything as I don't know what you're going to put in the specializations.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top