没有默认函数的C ++模板专业化 [英] C++ template specialization without default function

查看:139
本文介绍了没有默认函数的C ++模板专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码编译和工作良好:

I have the following code that compiles and works well:

template<typename T>
T GetGlobal(const char *name);

template<>
int GetGlobal<int>(const char *name);

template<>
double GetGlobal<double>(const char *name);

但是我想删除default也就是说,我想调用GetGlobal< t>

However I want to remove the "default" function. That is, I want to make all calls to GetGlobal<t> where 't' is not an int or a double an error.

例如,GetGlobal< char>()应该是一个编译时错误。

For example, GetGlobal<char>() should be a compile time error.

我试图删除默认函数,但是,如我想象的,我收到了很多错误..所以有一种方法来禁用它,并允许调用只有专门版本的函数?

I tried to just delete the default function, but, as I imagined, I received a lot of errors.. So is there a way to "disable" it and allow calls only to the specialized versions of the function?

谢谢!

推荐答案

编译时错误实现为:

template<typename T>
T GetGlobal(const char *name) { T::unimplemented_function; }
// `unimplemented_function` identifier should be undefined

如果使用Boost,它更优雅:

If you use Boost you could make it more elegant:

template<typename T>
T GetGlobal(const char *name) { BOOST_STATIC_ASSERT(sizeof(T) == 0); }

C ++标准保证没有这样的sizeof等于0的类型,得到编译时错误。

C++ Standard guarantees that there is no such type which has sizeof equal to 0, so you'll get a compile-time error.

由于 sbi 建议他的意见最后可以减少到:

As sbi suggested in his comments the last could be reduced to:

template<typename T>
T GetGlobal(const char *name) { char X[!sizeof(T)]; }

我喜欢第一个解决方案,因为它给出更清晰的错误消息(至少在Visual C ++中)比其他人。

I prefer the first solution, because it gives more clear error message (at least in Visual C++) than the others.

这篇关于没有默认函数的C ++模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆