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 (ie, for any T
)? Or what would be the best strategy to proceed, if that's not possible?
Thanks!
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();
}
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.