专业化和模板模板参数

时间:2011-01-10 14:40:59

标签: c++ templates

我有以下内容:

template <template <typename, typename> class C, class T, class A >
class TTCTest
{
public:
        TTCTest(C<T, A> parameter) { /* ... some stuff... */ }
        C<T, A> _collection;
};

我想确保模板只被实例化,其中T和A类是特定类型(分别是路径和分配器)。

例如:

...
list<path, allocator<path> > list1;
list<int, allocator<int> > list2;

TTCTest<list> testvar(list1); // ...should work
TTCTest<list> testvar(list2); // ...should not work
...

这是可能的,语法是什么?

此致 山口

2 个答案:

答案 0 :(得分:2)

你可以通过部分专业化来做到这一点,你无法为非专业案例提供实施 例如:

template <template <typename, typename> class C, class T, class A >
class TTCTest;

template <template <typename, typename> class C>
class TTCTest<C, path, allocator<path> >
{
  // ...
};

答案 1 :(得分:0)

您可以创建特征类来约束实例化。例如,仅将TTCTest构造限制为path类型:

template<class T, class A> class path {};
template<class T, class A> class not_path {};

template<class T> class allocation {};

template<class T>
struct Testable;

template<class T, class A>
struct Testable<path<T,A> > {};

template <template <typename, typename> class C, 
class T, class A >
class TTCTest
{
public:
        TTCTest(C<T, A> parameter, Testable<C<T,A> > = Testable<C<T,A> >());
        C<T, A> _collection;
};

void foo()
{
   path<int, allocation<int> > p;
   TTCTest<path, int, allocation<int> > t(p); // compiles

   not_path<int, allocation<int> > np;
   TTCTest<not_path, int, allocation<int> > t1(np); // fails
}

编辑: 由于您稍后指出您可能需要的是部分特化,在这种情况下它将如下所示:

template <class T, class A >
class TTCTest<path, T, A>
{
public:
        TTCTest(path<T, A> parameter);
        path<T, A> _collection;
};
相关问题