C++ 11查找类型是否具有成员函数或支持运算符的方法?

tmp*_*ppp 12 c++ c++11

有一种(貌似)很好的C++ 03方法可以找出一个类型是否有成员函数或运算符:

https://github.com/jaredhoberock/is_call_possible/blob/master/is_call_possible.hpp

有没有现代的C++ 11方法呢?最好不要包含任何外部代码并仅使用标准.

ken*_*ytm 21

这适用于GitHub中提供的所有测试用例(演示:http://ideone.com/ZLGp4R):

#include <type_traits>

template <typename C, typename F, typename = void>
struct is_call_possible : public std::false_type {};

template <typename C, typename R, typename... A>
struct is_call_possible<C, R(A...),
    typename std::enable_if<
        std::is_same<R, void>::value ||
        std::is_convertible<decltype(
            std::declval<C>().operator()(std::declval<A>()...)
            //                ^^^^^^^^^^ replace this with the member you need.
        ), R>::value
    >::type
> : public std::true_type {};
Run Code Online (Sandbox Code Playgroud)


zah*_*zah 16

C++ 11增加了一个新技巧,我经常开玩笑地称之为"CFINAE"(编译失败不是错误).

它利用了decltype运算符和SFINAE的常规属性.

考虑以下功能:

template <typename X, typename Y>
static auto check(X& x, Y& y) -> decltype(x >> y);
Run Code Online (Sandbox Code Playgroud)

这将只超载如果在被视为XY是移位算被定义为何种类型.添加一个常规的catch-all重载check,你有一个机制来测试是否可以编译任意表达式.

事实上,这是Andrew Sutton(Concepts Lite提案的作者之一)在实验Origin库中开发的原理.事实上,我的例子直接从这里开始实现Streamable概念.

我推荐Andrew Sutton和Bjarne Stroustrup撰写的GoingNative 2012的以下演示文稿,其中介绍了新概念和Origin库:

http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/A-Concept-Design-for-C-


Nic*_*las 2

不,这几乎是一样的。或多或少。尽管您可以使用标准库特征替换该实现内部使用的一些元函数,但实现有所不同。但是没有简单的方法来检测是否可以在给定一组参数的情况下调用某种类型的函数。

这是概念 (PDF)