【问题标题】:pointer to const member function typedef指向 const 成员函数 typedef 的指针
【发布时间】:2011-03-04 07:25:13
【问题描述】:

我知道可以像这样分开创建指向成员函数的指针

struct K { void func() {} };
typedef void FuncType();
typedef FuncType K::* MemFuncType;
MemFuncType pF = &K::func;

是否有类似的方法来构造指向 const 函数的指针?我试过在不同的地方添加 const ,但没有成功。我玩过一些 gcc,如果你对类似的东西进行模板推导

template <typename Sig, typename Klass>
void deduce(Sig Klass::*);

它会将 Sig 显示为函数签名,并在末尾添加 const。如果在代码中执行此操作,它会抱怨您不能在函数类型上使用限定符。似乎它应该以某种方式成为可能,因为扣除有效。

【问题讨论】:

    标签: c++ function pointers member


    【解决方案1】:

    另一种更直接的方法(避免usingtypedefs)是这样的:

    #include <iostream>
    
    class Object
    {
        int i_;
    public:
        int j_;
        Object()
            : Object(0,0)
        {}
        Object(int i, int j)
            : i_(i),
            j_(j)
        {}
    
        void printIplusJplusArgConst(int arg) const
        {
            std::cout << i_ + j_ + arg << '\n';
        }
    };
    
    int main(void)
    {
        void (Object::*mpc)(int) const = &Object::printIplusJplusArgConst;
    
        Object o{1,2};
        (o.*mpc)(3);    // prints 6
    
        return 0;
    }
    

    mpc 是一个指向Object 的常量方法指针。

    【讨论】:

      【解决方案2】:

      一个轻微的改进展示了如何在没有 typedef 的情况下做到这一点。 在如下推断的上下文中,您不能使用 typedef。

      template <typename Class, typename Field>
      Field extract_field(const Class& obj, Field (Class::*getter)() const)
      {
         return (obj.*getter)();
      }
      

      应用于带有 const getter 的类:

      class Foo {
       public:
        int get_int() const;
      };
      
      Foo obj;
      int sz = extract_field(obj, &Foo::get_int);
      

      【讨论】:

        【解决方案3】:

        你想要这个:

        typedef void (K::*MemFuncType)() const;
        

        如果你想仍然基于MemFuncTypeFuncType,你需要改变FuncType

        typedef void FuncType() const;
        typedef FuncType K::* MemFuncType;
        

        【讨论】:

        • 是的,你是对的!我以为我尝试了第二个,但猜不是,那是另一台机器,虽然可能是旧的编译器。明天必须再次检查。
        猜你喜欢
        • 1970-01-01
        • 2014-10-18
        • 2016-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多