문제

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;
}
도움이 되었습니까?

해결책

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 ...
};

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top