【问题标题】:how to check the size of an array during compile time [duplicate]如何在编译时检查数组的大小[重复]
【发布时间】:2017-12-11 12:45:16
【问题描述】:

我有这个代码:

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_asset 做到这一点?

【问题讨论】:

  • 如果大小应该是编译时间常数,为什么要使用std::vector 而不是std::array
  • 老式方法有什么问题:创建一个带 8 个参数的构造函数?
  • ......当你不希望它是可变参数时,为什么要使用可变参数列表? ;)
  • @tobi303 如何使用数组代替向量?
  • @Bathsheba 老式的很慢,因为向量(或数组)的初始化是在运行时而不是编译时完成的。

标签: c++ compilation static-assert


【解决方案1】:

当然:

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 个参数时收到的错误消息可能会令人困惑。这种情况下的断言有助于发出更好的错误消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2017-07-15
    • 2015-07-31
    • 2014-08-23
    相关资源
    最近更新 更多