gpt4 book ai didi

c++ - 将类型 int(C::*)(int, char) 转换为类型 int(int, char)

转载 作者:搜寻专家 更新时间:2023-10-31 01:10:09 24 4
gpt4 key购买 nike

我有一个类:

struct C {
int F(int, char) { return 0; }
};

我需要创建一个 std::function,它将为变量 c 调用 C::F 函数:

C c;
std::function<int(int, char)> f;
...
f = std::bind(&C::F, &c, _1, _2);

但是如果函数的签名被更改,我也需要更改 std::function。

所以我不想重复签名:

C c;
std::function<delete_class<decltype(&C::F)>::type> f;
...
f = std::bind(&C::F, &c, _1, _2);

其中 delete_class 是一些魔法助手,它将类型 int(C::*)(int, char) 更改为 int(int, char)

我怀疑我可以在 boost::mplboost::function_types 的帮助下实现它,但我做不到。

谁有经验,能告诉我怎么做吗?

附言。对比 2010

最佳答案

如果你需要一个类型特征 delete_class如您所愿,这个应该可以完成工作:

template<typename S>
struct delete_class;

template<typename R, typename C, typename... Ts>
struct delete_class<R (C::*)(Ts...)>
{
using type = R(Ts...);
};

然后将满足以下断言:

static_assert(
std::is_same<delete_class<decltype(&C::F)>::type,
int(int, char)
>::value, "!");

然后您可以使用 delete_class<>你提议的方式:

std::function<delete_class<decltype(&C::F)>::type> f;
C c;
f = std::bind(&C::F, &c, _1, _2);

这是一个live example .

编辑:

如果您仅限于 VC10 支持(即没有可变参数模板),您将必须定义 delete_class 的几个部分特化。主模板:

template<typename S>
struct delete_class;

template<typename R, typename C>
struct delete_class<R (C::*)()>
{
typedef R(type)();
};

template<typename R, typename T>
struct delete_class<R (C::*)(T)>
{
typedef R(type)(T);
};

template<typename R, typename T, typename U>
struct delete_class<R (C::*)(T, U)>
{
typedef R(type)(T, U);
};

template<typename R, typename T, typename U, typename V>
struct delete_class<R (C::*)(T, U, V)>
{
typedef R(type)(T, U, V);
};

// And so on...

关于c++ - 将类型 int(C::*)(int, char) 转换为类型 int(int, char),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16220269/

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