带有重载成员函数的C++std::mem_fn
C++ std::mem_fn with overloaded member function
编译以下代码时,Visual Studio会报告:
main.cpp(21): error C2664: 'std::_Call_wrapper<std::_Callable_pmd<int ClassA::* const ,_Arg0,false>,false> std::mem_fn<void,ClassA>(int ClassA::* const )' : cannot convert argument 1 from 'overloaded-function' to 'int ClassA::* const '
1> with
1> [
1> _Arg0=ClassA
1> ]
1> Context does not allow for disambiguation of overloaded function
为什么编译器在创建mem_fptr1
时会感到困惑?但是当我指定类型时,mem_fptr2
是可以的。
我可以创建一个不带参数的重载成员函数的成员函数指针吗?
class ClassA
{
public:
void memberfunction()
{
std::cout <<"Invoking ClassA::memberfunction without argument" << std::endl;
}
void memberfunction(int arg)
{
std::cout << "Invoking ClassA::memberfunction with integer " << arg << std::endl;
}
};
int main()
{
auto mem_fptr1 = std::mem_fn<void, ClassA>(&ClassA::memberfunction);
auto mem_fptr2 = std::mem_fn<void, ClassA, int>(&ClassA::memberfunction);
mem_fptr1(ClassA());
mem_fptr2(ClassA(), 3);
}
采用参数类型的可变列表的模板重载在C++11中引入,但在C++14中作为缺陷#2048被删除。指定特定重载的方法是指定一个函数类型作为第一个模板参数(第二个模板参数,类类型,可以省略,因为它可以推导出来):
auto mem_fptr1 = std::mem_fn<void()>(&ClassA::memberfunction);
auto mem_fptr2 = std::mem_fn<void(int)>(&ClassA::memberfunction);
然后函数类型R
与类类型T
组成为R T::*
,以给出成员函数类型。这也允许将std::mem_fn
形成为数据成员(其中R
是非函数类型)。
请注意,您的代码(用于mem_fptr2
)在C++14中不起作用,因为在C++14中将删除了采用变参数类型列表的模板重载;上述代码将适用于两个版本的标准。
另一种选择是执行成员函数铸造;在这种情况下,您不需要为mem_fn
:指定模板参数
auto mem_fptr1 = std::mem_fn(
static_cast<void (ClassA::*)()>(&ClassA::memberfunction));
auto mem_fptr2 = std::mem_fn(
static_cast<void (ClassA::*)(int)>(&ClassA::memberfunction));
相关文章:
- 在"template"和函数声明之间使用:template<typename trait> using tr = base_trait<trait> void fn(tr::t
- "double* grade"、"double *grade"和"double* fn()"有什么区别?
- 通过实用程序 fn 将捕获的 lambda 传递给 C 样式回调 - 错误
- v8 源代码中 ArrayMap 函数的回调 fn 参数是什么?
- (C++)如何在不导致 mem 泄漏的情况下将指针传递到分配了'new'的函数?
- 如何释放子阵列的mem,它是更大数组的一部分
- 为什么移动语义与动态 mem 分配中的浅拷贝具有相同的行为
- 标准库中是否有相当于 Rust 的 'std::mem::d rop' 的C++?
- 使用 new 而不是 malloc 分配 mem
- fn 指针的向量没有显示正确的大小()
- 为什么未初始化的指针会导致接近 0 的 mem 访问冲突
- .Net字符串是否可以在不复制的情况下交给fn(const char16_t*str)
- 新 X 在作为参数传递给函数时是否会导致 mem 泄漏
- 引用变量如何存储在mem中
- C++:将mem乐趣用于自己的结构
- 在CUDA中具有共享MEM的非方面矩阵转置
- 修改filter_iterator谓词以接受BOOST中的两个参数(二进制fn)
- 变分递归模板mem有趣的专业化
- 如何创建像"Fn"+Key_Up这样的QKeySequence
- 从 ZedBoard 上的 GNU Radio 访问 /dev/mem