gpt4 book ai didi

c++ - SFINAE 关于指向重载函数的指针

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:02:51 24 4
gpt4 key购买 nike

考虑以下程序。我使用 h() 作为帮助程序,通过指向来自 cmath 的重载函数的指针来解决歧义:

#include <cmath>

typedef double(*PF1)(double);
typedef double(*PF2)(double, double);
typedef double(*PF3)(double, double, double);
// etc...

auto h(PF1 p) -> decltype(p) {return p;}
auto h(PF2 p) -> decltype(p) {return p;}
auto h(PF3 p) -> decltype(p) {return p;}

int f(int) {return 0;}; // my math function

int main() {
//auto s_ = std::sin; // won't work as std::sin is overloaded
auto s = h(std::sin); // works, type of s is a double(*)(double)
auto p = h(std::pow); // OK.
// auto my_aim = h(f); // my aim is to make h() work with f too
}

是否有更智能或更通用的助手来推导指向(可能)重载函数的指针的类型,给定指向函数本身的指针,以便推导将“更喜欢”仅涉及 double 类型的重载(作为返回类型和参数)(如果可用),否则为其他重载之一。

最佳答案

以下内容可能会有所帮助:

constexpr auto h(double(*p)(double)) -> decltype(p) {return p;}
constexpr auto h(double(*p)(double, double)) -> decltype(p) {return p;}
constexpr auto h(double(*p)(double, double, double)) -> decltype(p) {return p;}

template <typename Return, typename ... Args>
constexpr auto h(Return (*p)(Args...)) -> decltype(p) {return p;}

int f(int) {return 0;}; // my math function

int main(int argc, char *argv[])
{
//auto s_ = std::sin; // won't work as std::sin is overloaded
auto s = h(std::sin); // works, type of s is a double(*)(double)
auto p = h(std::pow); // OK.
auto my_aim = h(f); // works too

return 0;
}

只要 h 参数在一个提供的 (double(*p)(double..)) 中或者没有重载(对于 f )(因此模板可以推断出它的类型)。

编辑

添加一个更通用的类来处理:

template<typename Sign, typename ... Signs>
struct identity : identity<Signs...>
{
using identity<Signs...>::h;
static constexpr auto h(Sign p) -> decltype(p) {return p;}
};

template<typename Sign>
struct identity<Sign>
{
static constexpr auto h(Sign p) -> decltype(p) {return p;}

template <typename T>
static constexpr auto h(T p) -> decltype(p) {return p;}
};

让我们在您的示例中使用它:

typedef identity<double(*)(double),
double(*)(double, double),
double(*)(double, double, double)> MyIdentity;

int f(int) {return 0;}; // my math function

int main(int argc, char *argv[])
{
auto s = MyIdentity::h(std::sin); // works : double(*)(double)
auto p = MyIdentity::h(pow); // works : double(*)(double, double)
auto my_aim = MyIdentity::h(f); // works : (int)(*)(int)

return 0;
}

关于c++ - SFINAE 关于指向重载函数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21074513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com