Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make function argument default to surrounding scope

Considering the following code/scheme provided below, is it somehow possible to omit the necessity to specify the this?

Is there a way to change the code so that a function/constructor automatically get the surrounding scope, maybe even as a template argument?

#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;
}
like image 758
vlad_tepesch Avatar asked Feb 16 '26 12:02

vlad_tepesch


1 Answers

You could add a member-function to ABase that create the Attr for you.

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};
    }
};

Then we can use it as

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
};
like image 180
super Avatar answered Feb 18 '26 00:02

super



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!