Choose Best Available Function Through Tag Inheritance

前端 未结 2 1164
借酒劲吻你
借酒劲吻你 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:35

    First, we define a priority class.

    template struct priority : priority {};
    template<> struct priority<0> {};
    

    It can be used to give a total order on the functions as follows:

    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>{}); }
    

    The Int template parameter and the decltype() make sure that only the defined functions compete for being called (keyword SFINAE). The priority tag class allows us to pick the best one among them.

    Note that the SFINAE part only works if you have at least one parameter on which you can template. If anyone has an idea on how to avoid this, please tell me.

提交回复
热议问题