C++ 类型特征来检查类是否有运算符/成员

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2122319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:10:00  来源:igfitidea点击:

C++ type traits to check if class has operator/member

c++classtemplatestypetraits

提问by Anycorn

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

可能的重复:
是否可以编写 C++ 模板来检查函数是否存在?

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::vectoras a template parameter has operator[], while std::pairdoes not.

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

回答by Georg Fritzsche

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

您无法通过类型特征解决此问题,因为您必须为每个可能的名称定义 if。

Hereare 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.

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

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).

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