通过标记继承选择最佳可用功能 [英] Choose Best Available Function Through Tag Inheritance

查看:159
本文介绍了通过标记继承选择最佳可用功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设用户定义了以下函数的一些子集:

Assume the user defines some subset of the following functions:

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

你的任务是写一个函数 call_best(int),它从上面列出的声明的函数中调用第一个函数(你可以认为它也是定义)。

Your task is to write a function call_best(int) which calls the first function from the above list that is declared (you may then assume that it is also defined). How do you do that?

推荐答案

首先,我们定义一个优先级类。

First, we define a priority class.

template<unsigned P> struct priority : priority<P-1> {};
template<> struct priority<0> {};

它可用于给出函数的总订单,如下所示:

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

template<class Int> auto call_best(Int i, priority<2>) -> decltype(f(i)) { return f(i); }
template<class Int> auto call_best(Int i, priority<1>) -> decltype(g(i)) { return g(i); }
template<class Int> auto call_best(Int i, priority<0>) -> decltype(h(i)) { return h(i); }

void call_best(int i) { call_best(i, priority<2>{}); }

Int 模板参数和 decltype()确保只有定义的函数竞争被调用(关键字SFINAE)。 priority 标签类允许我们选择其中最好的一个。

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.

请注意,如果您有至少一个参数可用于模板,则SFINAE部分才有效。如果任何人有一个想法,如何避免这一点,请告诉我。

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.

这篇关于通过标记继承选择最佳可用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆