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

有没有一种方法可以根据c++中的at template参数更改结构中使用的类型?

  •  0
  • trinalbadger587  · 技术社区  · 6 年前

    我想要的是一种根据模板参数为结构创建不同数据结构的方法

    template<uint32_t width, uint32_t height>
    struct S
    {
        templateif (width * height) > 32:
            uint64_t val;
        templateelse:
            uint32_t val;
        templatend;
    }
    

    就像你在上面看到的一样。是否有任何方法可以根据模板参数更改数据类型?

    我想这样的办法可能行得通:

    struct S
    {
        static const bool bit64 = (width * height) > 32;
        template <typename T>
        struct Arr
        {
            T val;
        }
        using DataType = Arr<bit64 ? uint64_t : uint32_t>;
        Arr data;
    }
    

    但没有。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Mestkon    6 年前

    你可以试试 std::conditional

    template<std::uint32_t width, std::uint32_t height>
    struct S
    {
        using type = typename std::conditional<(width * height > 32), 
            std::uint64_t, std::uint32_t>::type;
    
        type val;
    }