是否可以使用 SFINAE/模板来检查操作员是否存在?
我试图检查一个运算符在编译时是否存在,如果不存在我只想忽略它,有什么办法可以做到这一点吗?
示例运算符:
template <typename T>
QDataStream& operator<<(QDataStream& s, const QList<T>& l);
I'm trying to check if an operator exists at compile time, if it doesn't I just want it ignored, is there any way to do that?
example operator:
template <typename T>
QDataStream& operator<<(QDataStream& s, const QList<T>& l);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我最终使用了后备命名空间:
还找到了在编译时检查运算符的正确方法(尽管我将使用后备命名空间)。
或多或少基于 this :
//edit 稍微更改了 has_stream_operators 。
//编辑删除了链接,显然该网站有一些攻击javascript。
I ended up using a fallback namespace :
Also found the proper way to check for operators at compile time (although I'm going with the fallback namespace).
more or less based on this :
//edit changed has_stream_operators a bit.
//edit removed the link, apparently the site has some attack javascript.
这是一个老问题,但值得注意的是,Boost 刚刚为几乎所有操作员及其最新的 操作符类型特征。 OP 询问的特定运算符是使用
boost:has_left_shift
进行测试的。This is an old question but it's worth noting that Boost just added this ability for almost all operators with their newest Operator Type Traits. The specific operator OP asked about is tested with
boost:has_left_shift
.这不太容易,在 C++03 中通常也是不可能的。例如,如果您将
int*
和int*
用于op<<
,您将在编译时收到硬错误。因此,对于非类类型,您需要过滤掉标准禁止的类型。对于
op+
,我曾经为了好玩而写过这样的东西。请注意,我使用的是C
标头,因为我也需要使用clang
编译器来测试代码,而该编译器当时不支持我的 C++ 标头:当然,事后做测试非常重要
It isn't too easy and in C++03 it isn't in general possible. If you use
int*
andint*
forop<<
for example, you will get a hard error at compile time. So for non-class types, you need to filter out the types that the Standard forbids.For
op+
I once wrote such a thing for the kicks. Note that I'm usingC
headers, because I needed to test the code with theclang
compiler too, which at that time didn't support my C++ headers:Of course, it's very important to do tests afterwards