Question

I try to implement a template class and want to restrict it to be specialized for some given template class. For example, in following codes, I want to define the template class CTest that could be only specialized to std::vector<T> for some template parameter T. For other template parameters, the class should be undefined. How to implement the template class?

//   the interface should be something like following
//template <typename std::vector<T> >
//class CTest<std::vector<T> >;

int main(int argc, char* argv[])
{
    CTest<std::vector<int> > t1;    //  successful 
    CTest<std::vector<string> > t1; //  successful 
    CTest<int> t2;                  //  compile error
    return 0;
}
Was it helpful?

Solution

Leave the primary template undefined and only partially-specialize for the types you want to admit:

template <typename> class CTest;  // undefined


#include <vector>

template <typename T, typename Alloc>
class CTest<std::vector<T, Alloc>>
{
    // ... your template here ...
};

OTHER TIPS

Template specializations can be implemented with a completely different interface than the class template they specialize. There is no way to restrict which template specializations can exist.

If you want to have some influence on what can be used as template parameter, use template instantiation instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top