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

前端 未结 4 596
孤城傲影
孤城傲影 2020-12-08 03:22

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_ca

4条回答
  •  渐次进展
    2020-12-08 04:15

    C++ 11 adds a new trick, which I often jokingly call "CFINAE" (compilation failure is not an error).

    It makes use of the decltype operator and the regular properties of SFINAE.

    Consider the following function:

    template 
    static auto check(X& x, Y& y) -> decltype(x >> y);
    

    It will be considered during overloading only if X and Y are types for which the shift operator is defined. Add a regular catch-all overload for check and you have a mechanism to test whether an arbitrary expression can be compiled.

    And indeed, this is the principle developed in the experimental Origin library by Andrew Sutton (one of the authors of the Concepts Lite proposal). In fact, my example is taken straight from here to implement the Streamable concept.

    I recommend the following presentation from GoingNative 2012 by Andrew Sutton and Bjarne Stroustrup where they give an introduction to the new take on concepts and the Origin library:

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

提交回复
热议问题