Passing function as a class's template paremeter with unknown type

Viewed 58

I know we can do something like this:

void f1(){ printf("1"); }
void f2(){ printf("2"); }

template <void F()>
class A{
public:
    void func(){
        F();
    }
};

int main(){
    A<f1> a1; a1.func(); // printing "1"
    A<f2> a2; a2.func(); // printing "2"
}

Then, is it possible without knowing the return and argument types of the function f1 and f2? For example,

void f1(){ ... }
int f2(){ ... }

int main(){
    A<f1> a1; a1.f();
    A<f2> a2; a2.f();
}

Thanks.

1 Answers

In C++17, you might simply use auto

template <auto F>
class A{
public:
    void func(){
        F();
    }
};
Related