函数同时接受指向成员函数的指针和指向const成员函数的指针
Function taking both pointer to member-function and pointer to const member-function
我有以下代码库:
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)的指针时,此操作有效。但是,如果要传递指向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)...); }
// ...
}
};
现在,可以传递const-member-functions和non-const-member-functions。但是,现在,代码是重复的,可维护性降低了。
是否有一种方法可以将这两个函数合并为一个同时接受const-member-functions和non-const-member-functions的函数?
重要提示:我必须将指针函数作为形参(不能使用std::function)
编辑:我已经添加了一些代码。在函数内部,我构建了一个匹配成员函数签名的闭包(相同的返回类型和参数)。该闭包将被存储并在以后用于反射
你可以写一个类型trait,以此来告诉你某个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++构造函数成员初始化:传递参数
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 如何在C++通过公共函数访问私有函数成员?
- 解释了构造函数成员初始化列表
- 调用std::函数成员时内存损坏
- 是否可以为模板类的模板函数成员设置别名?
- 捕获 lambda 函数C++成员变量
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 获取与在模板参数中传递的函数成员类型相同的类
- 如何从公共函数成员访问地图私有成员
- C 构造函数成员分配优化
- 使用命名空间进行函数成员定义
- 函数成员作为 CUDA 内核的参数
- 模板基类函数成员的别名
- 函数成员中用于void和继承的enable_if
- 头文件中是否定义了一个很长的Class函数成员
- 类内/构造函数成员初始化
- 使用指向部分专用函数成员的指针自动填充向量
- 指向函数成员的指针