根据模板参数引用不同基类的函数 [英] Refer to function of different base class according to template parameter

查看:32
本文介绍了根据模板参数引用不同基类的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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;
}

有什么方法可以基于TC中的f函数映射到f1c2 中的 c1f2 ?当我使用 指向特定类时,我不清楚如何将 f 函数用作 f1f2 的包装器>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

注意:我不能修改 c1c2 类.它超出了我的范围.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆