【问题标题】:make function argument default to surrounding scope使函数参数默认为周围范围
【发布时间】:2019-12-18 14:39:07
【问题描述】:

考虑到下面提供的以下代码/方案,是否有可能省略指定 this 的必要性?

有没有办法更改代码,以便函数/构造函数自动获取周围的范围,甚至可以作为模板参数?

#include <iostream>

class AttrBase{
public:
  virtual int g()const = 0;
};

class ABase{
public:
 void reg(const char* name, AttrBase* att){
  std::cout << name << ": " << att->g()<< std::endl;
 }
};


class Attr : public AttrBase{
public: 
  Attr(const char* name, int val, ABase* parent /* = this */) // something like this
   :v(val)
  { 
    parent->reg(name, this);
  };
  int g()const override{return  v;};
  int v;
};


class D:public ABase{
  Attr a{"a", 1, this};
  Attr b{"b", 2, this};
  Attr c{"c", 3};    //< is this somehow possible
};

int main(){
 D d;
}

【问题讨论】:

  • 属性向其所属类的基类注册自身的目的是什么?
  • 向 ABase 添加受保护的方法:Attr MakeAttr(const char* name, int val) { return Attr(name, val, this); }。在D,你写Attr a{ MakeAttr("a", 1) };
  • @MichaelKenzel 这个问题并不清楚,但我怀疑这里的想法是使使用名称的字符串表示形式访问成员成为可能。如果这实际上是一个好主意是另一个问题。

标签: c++ default-arguments


【解决方案1】:

您可以向ABase 添加一个成员函数,为您创建Attr

class ABase{
public:
    void reg(const char* name, AttrBase* att) {
        std::cout << name << ": " << att->g()<< std::endl;
    }

protected:
    template <typename AttrType, typename... Args>
    AttrType make(Args&&... args) {
        return AttrType{std::forward<Args>(args)..., this};
    }
};

那么我们就可以把它当作

class D:public ABase {
    Attr a = make<Attr>("a", 1);
    auto b = make<Attr>("b", 2); // works with auto to avoid specifying the type twice
};

【讨论】:

    猜你喜欢
    • 2018-06-28
    • 2017-12-07
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 2014-10-05
    • 1970-01-01
    相关资源
    最近更新 更多