Reputation: 1385
I have two templates
template<typename Policy>
class X : public Policy
{ }
template<typename T>
class SimplePolicy
{ }
SimplePolicy
can be used as the template parameter to X
. Is it possible to specialize X
for all occurrences of SimplePolicy
-ies (i.e., for any T
)? Or what would be the best strategy to proceed, if that's not possible?
Thanks!
Upvotes: 0
Views: 67
Reputation: 4812
Yes it is possible using partial template specialization
#define STATIC_ASSERT(exp) \
typedef char static_assert_ ## __LINE__ [(exp) ? 1 : -1]
template<typename Policy>
class X : public Policy
{
public:
enum { value = 0 };
};
template<typename T>
class SimplePolicy
{ };
class CleverPolicy
{ };
template <typename T>
class X< SimplePolicy<T> > : public SimplePolicy<T>
{
public:
enum { value = 1 };
};
int _tmain(int argc, _TCHAR* argv[])
{
STATIC_ASSERT(X<SimplePolicy<int> >::value == 1);
STATIC_ASSERT(X<SimplePolicy<float> >::value == 1);
STATIC_ASSERT(X<CleverPolicy>::value == 0);
return 0;
}
Upvotes: 0
Reputation: 25613
Yes, you can do it like this:
#include <iostream>
using namespace std;
template<typename T>
class SimplePolicy
{ };
template<typename Policy>
class X : public Policy
{
public: void Do() { cout << "Standard" << endl; }
};
template<typename Inner>
class X<SimplePolicy<Inner> >
{
public: void Do() { cout << "Special" << endl; }
};
class A{};
int main()
{
X<A> xa;
X<SimplePolicy<A>> xs;
xa.Do();
xs.Do();
}
Upvotes: 1