使用constexpr验证构造函数中的文字参数

Ste*_*ini 3 c++ validation constexpr c++17 if-constexpr

我开始尝试constexpr.
我想要实现的是验证literal作为ctor参数提供的数值.
我开始使用以下内容,如果构造MyStruct 值<= 4 则抛出.

constexpr int validate(int v)
{
  return (v > 4) ? v : throw exception();
};

struct MyStruct final
{
  constexpr MyStruct(const int v)
    : _v{validate(v)}
  {
  }

  void add(int toAdd)
  {
    _v += toAdd;
  }

  int _v;
};

int main(int argc, char**)
{
  constexpr MyStruct a{500};  // ok so far...
  a.add(argc);                // ...nope 
  MyStruct b{500};            // check at runtime :(
  MyStruct c{argc};           // runtime check ok
}
Run Code Online (Sandbox Code Playgroud)

标记MyStructconstexpr按预期工作,但这会阻止调用,add因为它不可变.

我认为这可以完成,因为我只针对文字值(在编译时已知).
我想避免使用模板.

Jar*_*d42 5

函数参数不是const表达式: - /

您可以传递std::integral_constant<std::size_t, 4u>以允许构造函数内的编译时检查:

struct MyStruct final
{
    // For runtime or constexpr usage.
    constexpr MyStruct(int v) : _v{validate(v)} {}

    // For compile-time values
    template <std::size_t N>
    constexpr MyStruct(std::integral_constant<std::size_t, N>) : _v{N}
    {
        static_assert(N > 4, "Unexpected");
    }

    // ...
};
Run Code Online (Sandbox Code Playgroud)

然后

MyStruct b{std::integral_constant<std::size_t, 500>{}};
Run Code Online (Sandbox Code Playgroud)