根据模板参数引用不同基类的函数 [英] 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;
}
有什么方法可以基于T
把C
中的f
函数映射到f1
c2
中的 c1
和 f2
?当我使用 指向特定类时,我不清楚如何将
f
函数用作 f1
和 f2
的包装器>T
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
注意:我不能修改 c1
和 c2
类.它超出了我的范围.
Note: I cannot modify class c1
and c2
. its out of my scope.
推荐答案
您可以使用 constexpr if 来自 C++17.例如
You can use constexpr if from C++17. e.g.
void f() {
if constexpr (std::is_same_v<T, c1>)
f1();
else
f2();
}
请注意,constexpr if 在编译时被评估,正如@skypjack 评论的那样,对于这种情况,在运行时评估也很好.所以下面的代码也可以正常工作:
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();
}
这篇关于根据模板参数引用不同基类的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!