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

C++14 中如何方便地将 tuple 展开成为另一个 class 的 variadic template

  •  
  •   dangyuluo · 2022-07-20 04:02:35 +08:00 · 1555 次点击
    这是一个创建于 618 天前的主题,其中的信息可能已经有所发展或是发生改变。

    比如有一个 tuple, std::tuple<int, int, float>, 另一个类接受 variadic template

    template <typename... Ts>
    class MyClass{};
    

    请问这种情况下如何方便地将int, int, float传入MyClass,以实现MyClass<int, int ,float>呢?

    我能想到的办法就是写一个自己的TupleWrapper然后在类里包装一下 MyClass ,这里也可以做到模板。但是这样太麻烦了,请问有没有更简洁的办法呢?

    详见: https://godbolt.org/z/zMbPTT8Mz

    第 1 条附言  ·  2022-07-20 05:10:31 +08:00
    C++17 里倒是可以用 class template argument deduction 来做,不过就没办法是 constexpr 了

    https://godbolt.org/z/E9nhYqzj9
    第 2 条附言  ·  2022-07-20 05:13:06 +08:00
    哈哈天天想着特殊技巧,最基本的知识都忘了。用 class template specialization 就好了

    https://godbolt.org/z/Kedo5YYj6
    4 条回复    2022-07-21 17:13:10 +08:00
    darklights
        1
    darklights  
       2022-07-20 06:04:11 +08:00
    不知道你最终想实现什么。
    单就给的例子而言,C++11 都可以做的比较简洁。
    https://godbolt.org/z/chbefrdos
    darklights
        2
    darklights  
       2022-07-20 06:33:30 +08:00
    再来个 C++17
    https://godbolt.org/z/xf5vhqMnx

    看来 C++模板还修补得挺多。
    然并卵。
    dangyuluo
        3
    dangyuluo  
    OP
       2022-07-20 06:36:59 +08:00
    @darklights 我们还停留在 C++14 ,要是能用 17 的 folding expression 就简单多了,我又不想用`make_index_sequence`这种方法,想着有没有类似`std::apply`这种简单的语法
    xiaoxuxu
        4
    xiaoxuxu  
       2022-07-21 17:13:10 +08:00
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4384 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 10:05 · PVG 18:05 · LAX 03:05 · JFK 06:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.