C ++类型traits以检查类是否具有运算符/成员 [英] C++ type traits to check if class has operator/member

查看:190
本文介绍了C ++类型traits以检查类是否具有运算符/成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

是否可以编写一个C ++模板来检查函数的存在?

Possible Duplicate:
Is it possible to write a C++ template to check for a function's existence?

是否可以使用boost类型traits或一些其他机制来检查特定模板参数是否具有运算符/函数,例如 std :: vector 作为模板参数 operator [] ,而 std :: pair

Is it possible to use boost type traits or some other mechanism to check if a particular template parameter has an operator/function, e.g. std::vector as a template parameter has operator[], while std::pair does not.

推荐答案

你不能通过类型特征来解决这个问题,因为你必须定义是否为每个可能的名称。

You can't solve this via type traits because you'd have to define if for every possible name.

这里是列出的常见解决方案,但是有一个问题:许多STL实现将通用代码放在基类中,并且此方法不检查继承的名称。

Here are the common solutions listed, which have one problem though: many STL implementations put common code in base classes and this method doesn't check for inherited names.

如果您需要检查继承的成员也请参阅此处。答案提供了一个解决方案,检查所讨论的类是否有该名称的成员,并且还可以检查常量和参数计数。然而,它无法检查包括参数和返回类型的完整签名,并且成员可见性没有影响。您应该能够使用链接的 is_call_possible<> (还没有时间看看)。

If you need to check for inherited members too, see here. The answer provides a solution that checks whether the class in question has a member of that name and can also check for const-ness and argument count. It fails however to check for the full signature including argument and return types and member visibility doesn't make a difference. You should be able to solve that partially by using the linked is_call_possible<> (haven't had time yet too look at it).

这篇关于C ++类型traits以检查类是否具有运算符/成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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