How Can I Prevent Template Generation for Objects That Don't Implement a Method

后端 未结 1 731
借酒劲吻你
借酒劲吻你 2021-01-14 13:44

So for the purpose of example let\'s say I have 3 simple structs, the second of which doesn\'t contain a bar method:

struct one {
          


        
相关标签:
1条回答
  • 2021-01-14 14:34

    First, the utilities. One is our favorite overload that shows off three C++17 features, and overloads the operator() of several function objects, all in two lines.

    template<class... Ts> struct overload : Ts... { using Ts::operator()...; };
    template<class... Ts> overload(Ts...) -> overload<Ts...>;
    

    Then an accepts-everything fallback tag type:

    struct fallback_t { template<class T> fallback_t(T&&) {} };
    

    Now to the call itself. We make the original generic lambda SFINAE-friendly by putting the value.bar() call into the trailing return type, then overload it with a fallback overload that has undefined behavior if actually invoked (since OP "omit[ted] any explicit definition of behavior"):

    void bar(const int key) { 
        findObject(key, overload {
              [&](auto& value) -> decltype(void(value.bar())) { value.bar(); },
              [](fallback_t){ fire_missiles_and_impregnate_cat(); }
        } ); 
    }
    
    0 讨论(0)
提交回复
热议问题