gpt4 book ai didi

c++ - 同时采用指向成员函数的指针和指向 const 成员函数的指针的函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:07 25 4
gpt4 key购买 nike

我有以下代码库:

template <typename Type>
class SomeClass {
public:
template <typename ReturnType, typename... Params>
void register_function(const std::pair<std::string, ReturnType (Type::*)(Params...)> fct) {
auto f = [fct](Params... params) -> ReturnType { return (Type().*fct.second)(std::ref(params)...); }
// ...
}
};

当我将指针传递给成员函数(非常量)时,这会起作用。但是,如果我想将指针传递给 const 成员函数,则会导致编译错误,我必须复制上述函数才能获得此代码:

template <typename Type>
class SomeClass {
public:
template <typename ReturnType, typename... Params>
void register_function(const std::pair<std::string, ReturnType (Type::*)(Params...)> fct) {
auto f = [fct](Params... params) -> ReturnType { return (Type().*fct.second)(std::ref(params)...); }
// ...
}

template <typename ReturnType, typename... Params>
void register_function(const std::pair<std::string, ReturnType (Type::*)(Params...) const> fct) {
auto f = [fct](Params... params) -> ReturnType { return (Type().*fct.second)(std::ref(params)...); }
// ...
}
};

现在,我可以传递常量成员函数和非常量成员函数。但是,现在,代码是重复的,可维护性降低了。

有没有办法将这两个函数合并为一个同时采用常量成员函数和非常量成员函数的函数?

重要说明:我必须真正将指针函数作为参数(没有 std::function)。

编辑:我添加了更多代码。在函数内部,我构建了一个与成员函数签名匹配的闭包(相同的返回类型和参数)。这个闭包将被存储并稍后用于进行反射(more here)

最佳答案

你可以写一个类型特征,基于它会告诉你一些 MF 是否是 Type 上的指向成员函数的指针:

template <typename C, typename T>
struct is_pointer_to_member_helper : std::false_type { };

template <typename C, typename T>
struct is_pointer_to_member_helper<C, T C::*> : std::is_function<T> { };

template <typename C, typename T>
struct is_pointer_to_member : is_pointer_to_member_helper<C,
std::remove_cv_t<T>
> { };

并用它来确保你只得到其中之一:

template <typename Type>
class SomeClass {
public:
template <typename MF>
std::enable_if_t<is_pointer_to_member<Type, MF>::value>
register_function(const std::pair<std::string, MF> fct)
{
auto f = [fct](auto&&... params) {
return (Type{}.*fct.second)(std::forward<decltype(params)>(params)...);
};

// ...
}
};

关于c++ - 同时采用指向成员函数的指针和指向 const 成员函数的指针的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31276652/

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