代码之家  ›  专栏  ›  技术社区  ›  intrigued_66

从间接模板参数中隐式选择数组元素类型和大小

c++
  •  1
  • intrigued_66  · 技术社区  · 2 年前

    我有一个类,根据模板参数的值,我想更改数组的元素类型和大小。

    下面的内容显然没有编译,但我用它来展示我想做什么。

    struct A{};
    struct B{};
    
    template<size_t N>
    class C
    {
        // This is illegal syntax, just using it as pseudo-code
        if constexpr(N <= 5)
        {
            std::array<A, 20> _array;
        }
        else
        {
            std::array<B, 80> _array;    
        }
    };
    

    ( N 不是数组的大小)

    我知道我可以通过 A 20 作为另外两个模板参数,但有办法避免这样做吗?

    2 回复  |  直到 2 年前
        1
  •  3
  •   Christian Stieber    2 年前

    按照以下思路做一些事情:

    #include <type_traits>
    
    template<size_t N> class C {
        typedef std::array<A,20> First;
        typedef std::array<B,80> Second;
        typename std::conditional<N<=5, First, Second>::type _array;
        // C++14 and later lets you to do this:
        // std::conditional_t<N<=5, First, Second> _array;
    };
    
        2
  •  1
  •   Chris    2 年前

    否定了Christian Stieber的答案,但进行了修改,将所有计算都放在模板参数中。 N 是唯一需要提供的模板参数,但其他参数 可以 可以使其更加灵活。

    #include <type_traits>
    #include <array>
    
    struct A {};
    struct B {};
    
    template<
        std::size_t N, 
        typename F = std::array<A, 20>, 
        typename S = std::array<B, 80>,
        typename T = typename std::conditional<N <= 5, F, S>::type
    > 
    class C {
        T _array;
    };
    

    在…上 godbolt .