Choose Best Available Function Through Tag Inheritance

前端 未结 2 1144
借酒劲吻你
借酒劲吻你 2021-01-07 00:21

Assume the user defines some subset of the following functions:

void f(int) {}
void g(int) {}
void h(int) {}
// ...

Your task is to write a

2条回答
  •  孤街浪徒
    2021-01-07 00:37

    Your code will work if you follow the convention of giving your functions a deduced return type (i.e auto/decltype(auto)). This can only be done in C++14 wherein a function with a deduced return type cannot be used until it is defined (even in an unevaluated operand), causing a substitution failure otherwise. Here's your example that works in clang 3.5 but unfortunately not in g++ 4.9.

    template struct priority : priority {};
    template<> struct priority<0> {};
    
    // ********
    auto f(int);
    auto g(int);
    auto h(int) { std::cout << "h()"; }
    // ********
    
    template auto call_best(Int i, priority<2>) -> decltype(f(i)) { return f(i); }
    template auto call_best(Int i, priority<1>) -> decltype(g(i)) { return g(i); }
    template auto call_best(Int i, priority<0>) -> decltype(h(i)) { return h(i); }
    
    void call_best(int i) { call_best(i, priority<2>{}); }
    
    int main()
    {
        call_best(0); // calls h()
    }
    

    clang 3.5 g++ 4.9

提交回复
热议问题