Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

c++ - C++11 ways of finding if a type has member function or supports operator?

There is a (seemingly) nice C++03 way of finding out if a type has a member function or operator:

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

Is there no modern C++11 way to do this? It would be better not having to include any external code and use only the standard.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This works with all test cases given in the GitHub (Demo: 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 {};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...