块非专用模板 c++
是否可以以某种方式禁止对未明确编写专门化的类型使用模板化函数。我的意思是,
template <typename T>
void foo(){}
template <>
void foo<int>(){}
int main(int argc, char* argv[]){
foo<int>(); //ok
foo<char>(); //Wrong - no specialized version for char.
}
我不能跳过函数的通用版本,因为编译器说,当我尝试专门化时, foo 不是模板函数。我可以简单地编写一些不能在通用函数中编译的内容,并添加一些注释来解释原因,但这将是非常无信息的。我想做的是能够直接导致编译器出现“foo()未定义”之类的错误。
Is it possible to somehow forbid using templated function for types for which specialization was not explicitly written. I mean something like that
template <typename T>
void foo(){}
template <>
void foo<int>(){}
int main(int argc, char* argv[]){
foo<int>(); //ok
foo<char>(); //Wrong - no specialized version for char.
}
I cannot skip generic version of function, cause then compiler says, that foo is not a template function when i try to specialize. I could simply write something that does not compile in generic function, and add some comment explaining why, but this would be quite non-informative. What i would like to do, is to be able to directly cause compiler to go with error like "foo() is not defined".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然:只要不定义它,如果您尝试使用它,您将收到链接器错误:
或者,您可以使用静态断言的某些变体来给出“更好的”编译时错误。以下是使用 C++0x
static_assert
的示例。请注意,您必须使false
值依赖于模板参数,否则在解析模板时可能会触发static_assert
。请注意,通常最好不要专门化函数模板。相反,最好委托给专门的类模板:
Sure: just don't define it and you'll get a linker error if you try to use it:
Alternatively, you can use some variation of a static assert to give a "nicer" compile-time error. Here is an example using the C++0x
static_assert
. Note that you must make thefalse
value dependent upon the template parameter, otherwise thestatic_assert
may be triggered when the template is parsed.Note that it's usually best not to specialize function templates. Instead, it is better to delegate to a specialized class template:
当然,只是不提供默认通用模板的定义。
Sure, just don't supply definition for the default generic template.