V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
csfreshman
V2EX  ›  程序员

C++求教:如何优雅实现运行时类型选择

  •  
  •   csfreshman · 2022-11-12 23:16:30 +08:00 · 1508 次点击
    这是一个创建于 502 天前的主题,其中的信息可能已经有所发展或是发生改变。

    公司内部框架有如下类定义:

    class SomeComputeClass {
    public:
        using SomeType = comm:HighPerfMap<std::sharded_ptr<std::vector<int>>,uint64_t,int>
        
        using CacheKeyType = typename  SomeType:key;
        //后面还有类型依赖 CacheKeyType
    };
    

    这里框架实现的时候 SomeType 将类型写死了,现在新增加了业务,需要新增一种类型,需要根据运行时传入的配置决定是用原来的 SomeType 类型,还是新增的类型。 本意是想实现:

    class SomeComputeClass {
    public:
        if(业务 == A){
            using SomeType = comm:HighPerfMap<std::sharded_ptr<std::vector<int>>,uint64_t,int>
        }else {
            using SomeType = comm:HighPerfMap<std::sharded_ptr<std::vector<int>>,int,int,int,int,int>
        }
        
    
        using CacheKeyType = typename  SomeType:key;
        //后面还有类型依赖 CacheKeyType
    };
    

    但运行时拿到的业务类型,编译时如何搞定呢? 请教各位有没有好的方法实现?

    6 条回复    2022-11-14 09:19:35 +08:00
    csfreshman
        1
    csfreshman  
    OP
       2022-11-12 23:26:18 +08:00
    有没有没睡的大佬来讨论下
    liuhan907
        2
    liuhan907  
       2022-11-12 23:54:29 +08:00 via Android
    运行时没有办法,你可以用模板加 sfinae 来编译期决定类型,用继承添加类型,运行时根据传入类型决定创建的实际子类
    AlohaV2
        3
    AlohaV2  
       2022-11-13 10:47:27 +08:00
    运行期的话感觉只能让 SomeComputeClass 继承自某一基类,然后在继承类里决定 SomeType. 但我感觉这样很多编译期的优化都无用了,代码复用性也不好。

    可以在定义"业务"的 type traits ,

    struct BusinissATraits {
    using SomeType = comm:HighPerfMap<std::sharded_ptr<std::vector<int>>,uint64_t,int>;

    };

    struct BusinessBTraits {
    using SomeType = comm:HighPerfMap<std::sharded_ptr<std::vector<int>>,int,int,int,int,int>;
    };


    template <typename BusinessT>
    class SomeComputeClass {
    using SomeType = typename BusinessT::SomeType;

    void Foo() {
    if constexpr (std::is_same_v<BusinessT, BussinessATraits) {
    }
    else if (...) {
    }
    }
    };
    yulon
        4
    yulon  
       2022-11-13 17:32:19 +08:00
    没有共同方法用变体、有共同方法用多态
    csfreshman
        5
    csfreshman  
    OP
       2022-11-13 23:42:20 +08:00
    @AlohaV2 多谢,目前来看只能改动改动这个框架代码了(妈的实在不想改,一改可能要改出问题,还要测另一个业务)
    liuidetmks
        6
    liuidetmks  
       2022-11-14 09:19:35 +08:00
    既然这么抵触,干嘛还想优化?随便打完收工不好吗
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   950 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 21:05 · PVG 05:05 · LAX 14:05 · JFK 17:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.