我有一个模板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
。
非常感谢。我想我正在寻找一些太复杂的东西。 – ereOn
@Schnommus但是如果你确实定义了类并且它有一个static_assert,它不应该永远不会被实例化,因为专业化比较好? –
这是不好的决定,因为连接阶段会发出错误,而不是编译。你永远不会知道你在哪里使用非专业课程。 – vladon