how to check the size of an array during compile time [duplicate]

问题内容:

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?

问题评论:

4  
why do you use std::vector and not std::array if the size should be a compile time constant?
2  
What’s wrong with the old-fashioned way: create a constructor taking 8 arguments?
1  
…and why do you use a variadic parameter list when you dont want it to be variadic ? 😉
    
@tobi303 How to use an array instead of a vector?
– mans
3 hours ago
    
@Bathsheba old fashioned is slow as the initialization of vector (or array) is done during run time and not compile time.
– mans
3 hours ago

答案:

答案1:

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.

答案评论:

原文地址:

https://stackoverflow.com/questions/47753302/how-to-check-the-size-of-an-array-during-compile-time

添加评论

友情链接:蝴蝶教程