Search code examples
c++compilationstatic-assert

how to check the size of an array during compile time


I have this code:

template<char... Ts>
class  myIDClass 
{
protected:
       std::vector<uint8_t> m_ID = { Ts... };

public:
       std::vector<uint8_t> getID()
        {
             return m_ID;
        }
}

and I can use it in this way:

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

MyClass mc;

But I want to make sure that the person that uses myIDClass enter exactly 8 character to enter as template parameter to the class. How can I do during compilation?

Is there anyway that I can do this using of static_asset?


Solution

  • Sure:

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

    However, since you know at compile time that you want exactly 8 values, you can use std::array instead:

    #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;
        }
    };
    

    In this case, you don't need the static_assert anymore. However, the error message the user of the template gets when not using exactly 8 arguments can be confusing. The assertion in this case helps with giving out a better error message.