How to prevent non-specialized template instantiation?(如何防止非专业模板实例化?)
问题描述
我有一个模板化的class(称之为Foo),它有几个专门化.如果有人尝试使用 Foo 的非专业版本,我希望编译失败.
I have a templated class (call it Foo) which has several specializations. I would like the compilation to fail if someone tries to use an unspecialized version of 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;
}
没有.
显然,编译器链只会在链接过程发生时发出警告.但是有没有办法让它在之前抱怨?
Obviously, the compiler chain only complains when the linking process takes place. But is there a way to make it complain before ?
我可以使用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;
}
为什么会这样?仅仅是因为没有任何通用模板.声明,是,但未定义.
Why does this work? Simply because there isn't any generic template. Declared, yes, but not defined.
这篇关于如何防止非专业模板实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何防止非专业模板实例化?
基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
