简体   繁体   中英

Is there a way to call varying function of member object based on template variable

I have the following code:

class Person {
  void func1() {
    obj_.function1();
  }

  void func2() {
    obj_.function2();
  }

  void func3() {
    obj_.function3();
  }

  Object obj_;
};

It's pretty obvious there is a pattern here...

I would like to know if I can call different functions based on template argument. the functions inside Object are regular member functions.

Is there any way to do something like the following?

class Person {
  
  template <typename Func>
  void generic() {
    obj_.Func();
  } 

  Object obj_;
};

Another question: Is there a type for function?

I believe it's the key point for it's doable or not.

Thanks

 template <auto Func>
 void generic() {
   (obj_.*Func)();
 } 

Then foo.generic<&Object::function1>() calls function1.

Prior to :

 template <void (Object::*Func)()>
 void generic() {
   (obj_.*Func)();
 } 

should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM