Home > Enterprise >  The correct syntax of a member which is a class template
The correct syntax of a member which is a class template

Time:10-16

I have a class :

      template<typename F1, typename F2, typename F3>
      class A {
        F1 f1;
        F2 f2;
        F3 f3;

        A(F1 f1_, F2 f2_, F3 f3_) : f1{f1_}, f2{f2_}, f3{f3_} {};

         apply_f1() {f1();};
         apply_f2() {f2();};
         apply_f3() {f3();};
         
       }

and have the following class where I need to instantiate class A with certain lambda functions. My lambda functions require that I capture this since I need certain class members within the lambda. The required interface of the lambdas: [this](void)->void

    class B {
         A a // How to instantiate it correctly. 
        // .. other stuff.
    }

Since I dont know how to instantiate A within class B as a member, So far what I have done is creating a static instance of class A within the constructor of class B like this:

B::B(){

   auto f1 = [this]() {....};
   auto f2 = [this]() {....};
   auto f3 = [this]() {....};
   static A a = A(f1,f2,f3);
   SomeEventRegisterClass(a);

}

The SomeEventRegisterClass will essentially register the instance of class A and for now let us just assume that it knows which of the lambdas (apply_f1, apply_f2, apply_f3) to invoke on certain events. In the example above I must declare the variable a static because otherwise if just declared locally it will go out of scope right after the constructor has finished. Therefore, when a particular event triggers and SomeEventRegisterClass attempts to use the instance of class A its lambda's will have been gone out of scope.

The fix with using static above is giving other problems; a simple one when used in the GTEST framework and you are running several tests in one executable, the static will only be defined once. Therefore, I am trying to see if it is possible to create such instance per class and where the lambdas will have same scope as class B

CodePudding user response:

You could declare a as A<std::function<void()>, std::function<void()>, std::function<void()>>. That will let it accept capturing lambdas:

#include <functional>

class B {
public:
    B() : a([this] {}, [this] {}, [this] {}) {}

private:
    A<std::function<void()>, std::function<void()>, std::function<void()>> a;
};

Note that the A constructor must be made public too.

  • Related