模板参数的模板专门化

时间:2014-05-07 11:38:12

标签: c++ templates

我有两个模板

template<typename Policy>
class X : public Policy
{ }

template<typename T>
class SimplePolicy 
{ }

SimplePolicy可用作X的模板参数。是否可以针对X的所有事件(即任何SimplePolicy)专门化T?或者,如果不可能,最好的策略是什么?

谢谢!

2 个答案:

答案 0 :(得分:1)

是的,你可以这样做:

#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();
} 

答案 1 :(得分:0)

是的,可以使用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;
}