是否可以防止在没有专门化的情况下使用C++模板

Is it possible to prevent a C++ template being used without specialization?

本文关键字:情况下 模板 C++ 专门化 是否      更新时间:2023-10-16

是否可以防止在没有专门化的情况下使用C++模板?

例如,我有

template<class T>
void foo() {}

我不希望它在没有专门用于foo<int>foo<char>的情况下使用。

您应该能够声明函数,而无需在泛型情况下实际定义它。这将导致对非专用模板的引用发出"未定义的符号"链接器错误。

template<class T>
void foo();
template<>
void foo<int>() {
    // do something here
}

这对我使用clang++来说很好。

您可以在函数体中使用未定义的类型。您将得到编译时错误消息:

template<class T> struct A;  
template<class T>  
void foo()  
{  
   typename A<T>::type a;  // template being used without specialization!!!
   cout << "foo()n";  
}  
template<>  
void foo<int>()  
{  
   cout << "foo<int>n";  
}  
template<>  
void foo<char>()  
{  
   cout << "foo<char>n";  
}  
int main()  
{  
  foo<int>();  
  foo<char>();  
//  foo<double>();   //uncomment and see compilation error!!!
}  

当foo函数有参数时,这是可能的。例如:template void foo(T param){}现在,你可以调用foo(1),foo('c')而不需要专门化。