gpt4 book ai didi

C++。如何将 const_cast 指针指向成员函数?

转载 作者:太空狗 更新时间:2023-10-29 20:26:59 25 4
gpt4 key购买 nike

#include <iostream>

template <typename Type, typename ReturnType>
struct mem_fun_ptr_t
{
typedef ReturnType (Type::*Func)();
Func func;
public:
mem_fun_ptr_t(Func f):
func(f) {}
ReturnType operator () (Type *p) { return (p->*func)(); }
};

// non-const version
template <typename T, typename R>
mem_fun_ptr_t<T, R> mem_fun_ptr(R (T::*Func)())
{
return mem_fun_ptr_t<T, R>(Func);
}

// const version
template <typename T, typename R>
mem_fun_ptr_t<T, R> mem_fun_ptr(R (T::*Func)() const)
{
typedef R (T::*f)();
f x = const_cast<f>(Func); //error
return mem_fun_ptr_t<T, R>(x);

//but this works:
/*
f x = reinterpret_cast<f>(Func);
return mem_fun_ptr_t<T, R>(x);
*/
}

int main()
{
std::string str = "Hello";
auto x = mem_fun_ptr(&std::string::length);
std::cout << x(&str);
return 0;
}

我想你已经猜到我在写什么了。是的,我应该用 Func const func 实现 mem_fun_ptr_t<>;属性。这将是正确的解决方案。但我正在学习,我想知道所有。那么如何const_cast成员函数指针呢?我试过了 f x = const_cast<f*>(Func)但我收到错误。

感谢您的反馈

最佳答案

同时将成员函数指针的类型传递给您的模板:( Live at ideone.com ):

template <typename Type, typename ReturnType, typename MemFuncType>
struct mem_fun_ptr_t
{
MemFuncType func;
public:
mem_fun_ptr_t(MemFuncType f) :
func(f) {}
ReturnType operator () (Type *p) const { return (p->*func)(); }
};

// non-const version
template <typename T, typename R>
mem_fun_ptr_t<T, R, R (T::*)()>
mem_fun_ptr(R (T::*Func)())
{
return mem_fun_ptr_t<T, R, R (T::*)()>(Func);
}

// const version
template <typename T, typename R>
mem_fun_ptr_t<const T, R, R (T::*)() const>
mem_fun_ptr(R (T::*Func)() const)
{
return mem_fun_ptr_t<const T, R, R (T::*)() const>(Func);
}

关于C++。如何将 const_cast 指针指向成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17626102/

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