V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
dangyuluo
V2EX  ›  C++

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

  •  
  •   dangyuluo · Jul 20, 2022 · 2522 views
    This topic created in 1391 days ago, the information mentioned may be changed or developed.

    比如有一个 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

    Supplement 1  ·  Jul 20, 2022
    C++17 里倒是可以用 class template argument deduction 来做,不过就没办法是 constexpr 了

    https://godbolt.org/z/E9nhYqzj9
    Supplement 2  ·  Jul 20, 2022
    哈哈天天想着特殊技巧,最基本的知识都忘了。用 class template specialization 就好了

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

    看来 C++模板还修补得挺多。
    然并卵。
    dangyuluo
        3
    dangyuluo  
    OP
       Jul 20, 2022
    @darklights 我们还停留在 C++14 ,要是能用 17 的 folding expression 就简单多了,我又不想用`make_index_sequence`这种方法,想着有没有类似`std::apply`这种简单的语法
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3879 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 04:47 · PVG 12:47 · LAX 21:47 · JFK 00:47
    ♥ Do have faith in what you're doing.