是否可以防止在没有专门化的情况下使用C++模板
Is it possible to prevent a C++ template being used without specialization?
是否可以防止在没有专门化的情况下使用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')而不需要专门化。
相关文章:
- 在没有参数列表的情况下使用模板名称"Event"无效,模板问题
- 模板方法访问正向声明的类仅在没有此指针的情况下无法编译
- G++ C++17 类模板参数推导在非常特殊的情况下不起作用
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 是否可以在不扣除的情况下将模板参数转发到 make_*?
- 在不使用模板的情况下获取 std::array 引用
- 如何在给定 std::variant 的情况下检索模板参数包?
- 在这种情况下,为什么模板即时深度超过限制?
- 简单情况下的模板缓冲区行为(GL_ALWAYS、GL_LEQUAL)
- 如何将左值传递给函数,仅在没有模板的情况下获取右值
- 在不模板化类的情况下存储 lambda
- 在不编写显式 setter 的情况下修改私有类数据成员的便捷方法是什么?模板有用吗?
- 类成员在继承的情况下用作模板参数
- 在这种情况下如何使用模板
- 如何在不更改类模板的情况下为模板类的模板方法添加第二种类型?
- 为什么在这种情况下c++模板参数推导失败
- 如何在不模板化类的情况下模板化成员变量
- 在这种情况下模板参数推导是如何工作的
- 为什么在一种情况下模板参数需要volatile,而在另一种情况下不需要