Search code examples
c++templatesc++14raii

emulate a function that propagate into every field like operator= and destructor


As I understand, there are some special functions that propagate to every field members by default. :-
copy assignment, copy constructor, move assignment, move constructor, destructor, etc.

class B{};
class C{B b;};     
C c1;  C c2;
c1=c2; //<-- automatic invoke B::operator=()

Is it possible to deploy some C++ trick to create/emulate a custom function that has such a cool feature?

If no, it is a complete answer.
If yes, please show demo ; I believe it should be a free function e.g. :-

class A{};
class B{};
void f(A a){}
class C{public: A a;B b;};     
//no need to code "void f(C c){f(c.a);}"
C c1;  
f(c1);  //<-- automatic invoke f(c1.a), but not invoke f(c1.b)

Template function and SFINAE might be useful but I don't know how to apply in this case.

I think it may be useful for some more advance RAII.


Solution

  • Write as_tie:

    struct C{
      A a;
      B b;
      friend auto as_tie(C& c){
        return std::tie(c.a, c.b);
      }
    };
    

    you need to write this for every type you want to interact with in this way; there is no way to avoid that until compile-time reflection arrives in C++. However, as_tie makes things like ==, swap, and the like easy to implement, so you get bonus payoff.

    After that, a mixture of foreach-tuple-element, override set objects, y-combinators, and invoke-if-possible gives you the ability to say "recursively apply f to each of its members".

    Barring you having to do this dozens of times in a variety of contexts, it won't be worth it.

    In short, no, not really. But maybe sorta with a lot of work.