如何防止非专门化模板实例化
How to prevent non-specialized template instantiation?
我有一个模板化的class
(称为Foo
),它有几个专门化。如果有人试图使用Foo
的非专门化版本,我希望编译失败。
下面是我实际得到的:
template <typename Type>
class Foo
{
Foo() { cannot_instantiate_an_unspecialized_Foo(); }
// This method is NEVER defined to prevent linking.
// Its name was chosen to provide a clear explanation why the compilation failed.
void cannot_instantiate_an_unspecialized_Foo();
};
template <>
class Foo<int>
{ };
template <>
class Foo<double>
{ };
:
int main()
{
Foo<int> foo;
}
作品:
int main()
{
Foo<char> foo;
}
。
显然,编译器链只有在链接过程发生时才会报错。但是有没有办法让它提前抱怨呢?
我可以用boost
不要定义类:
template <typename Type>
class Foo;
template <>
class Foo<int> { };
int main(int argc, char *argv[])
{
Foo<int> f; // Fine, Foo<int> exists
Foo<char> fc; // Error, incomplete type
return 0;
}
为什么这个工作?原因很简单,因为不是任何通用模板。
您可以简单地不定义基本大小写:
template <typename> class Foo; // no definition!
template <> class Foo<int> { /* ... */ }; // Foo<int> is OK
c++ 0x的一个技巧(也可用于c++ 03 static_assert
仿真,但错误消息不一定比保留未定义的主模板更好):
template<typename T>
struct dependent_false: std::false_type {};
template<typename Type>
struct Foo {
static_assert( dependent_false<Type>::value
, "Only specializations of Foo may be used" );
};
断言只有在Foo
用主模板实例化时才会触发。使用static_assert( false, ... )
将始终触发断言。
相关文章:
- 从C++实例化QML
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 约束和显式模板实例化
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 对象实例化调用构造函数的次数太多
- 如何使用非默认构造函数实例化模板化类
- 静态数据成员模板专用化的实例化点在哪里
- 错误的cv::face FacemarkLBF实例化
- C++的解析器在可以区分比较和模板实例化之前会做什么?
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- 检查某些类型是否是模板类 std::optional 的实例化
- 如何避免为模板化迭代器的每个可能的实例化专门化iterator_traits?
- 模板专门化的隐式实例化
- c++模板函数:显式实例化一个或多个专门化
- 专门化后的显式实例化
- 实例化后的显式专门化
- 即使具有显式实例化,也不会为显式专门化模板生成代码
- 如何防止非专门化模板实例化