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

如何在编译时检查数组的大小[重复]

  •  2
  • mans  · 技术社区  · 8 年前

    我有以下代码:

    template<char... Ts>
    class  myIDClass 
    {
    protected:
           std::vector<uint8_t> m_ID = { Ts... };
    
    public:
           std::vector<uint8_t> getID()
            {
                 return m_ID;
            }
    }
    

    我可以这样使用它:

    class   MyClass: myIDClass<'1','2','3','4','5','6','7','8'>
    {
      // some code here
    }
    
    MyClass mc;
    

    但我想确保使用myIDClass的人输入8个字符作为类的模板参数。编译期间我该怎么做?

    我是否可以使用static\u asset来完成此操作?

    1 回复  |  直到 8 年前
        1
  •  2
  •   Nikos C.    8 年前

    当然:

    template<char... Ts>
    class myIDClass
    {
        static_assert(sizeof...(Ts) == 8, "myIDClass needs 8 template arguments");
    
        // ...
    

    然而,由于您在编译时知道需要的值正好是8,所以可以使用 std::array 而是:

    #include <array>
    // ...
    
    template<char... Ts>
    class  myIDClass 
    {
        // The assertion is not actually needed, but you might still want to keep
        // it so that the user of the template gets a better error message.
        static_assert(sizeof...(Ts) == 8, "myIDClass needs 8 template arguments");
    
    protected:
        std::array<uint8_t, 8> m_ID = { Ts... };
    
    public:
        std::array<uint8_t, 8> getID()
        {
            return m_ID;
        }
    };
    

    在这种情况下,您不需要 static_assert 不再但是,模板用户在不使用8个参数时收到的错误消息可能会令人困惑。本例中的断言有助于发出更好的错误消息。