如何prevent非专业模板实例? [英] How to prevent non-specialized template instantiation?
本文介绍了如何prevent非专业模板实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个模板类
(称之为富
),其中有几个专业。我想编译失败,如果有人试图使用一个版本的非专业化富
。
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 ?
我可以使用升压
。
推荐答案
只是不定义类:
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.
这篇关于如何prevent非专业模板实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文