Raghu DV Raghu DV - 29 days ago 10
C++ Question

Refer to function of different base class according to template parameter

#include <iostream>
using namespace std;

class c1 {
public:
void f1() { std::cout << "In f1\n"; }
};

class c2 {
public:
void f2() { std::cout << "In f2\n"; }
};

template<typename T>
class C: public c1, c2 {
public:
void f() {

};
};

int main() {
C<c2> c;
c.f();

return 0;
}


is there any way based on
T
the function
f
in
C
can be mapped to function
f1
in
c1
and
f2
in
c2
? I am not clear how function
f
that can be used as a wrapper around
f1
and
f2
when i am pointing to a specific class using
T


Note: I cannot modify class
c1
and
c2
. its out of my scope.

Answer Source

You can use constexpr if from C++17. e.g.

void f() {
    if constexpr (std::is_same_v<T, c1>)
        f1();
    else
        f2();
}

LIVE

Note that constexpr if is evaluated at compile-time, as @skypjack commented, for this case, it's pretty fine to be evaluated at run-time too. So the following code works fine too:

void f() {
    if (std::is_same_v<T, c1>)
        f1();
    else
        f2();
}