可选扔在constexpr?

时间:2018-05-05 03:56:35

标签: c++11 error-handling

当我注意到某些代码中有一种不寻常的抛出模式时,我正在研究如何在这个repo https://github.com/elbeno/constexpr中为玩具项目实现编译时strlen。它似乎什么都不做,你为什么要这样做?

namespace err {
    extern const char * strlen_runtime_error;
}
constexpr int strlen(const char * str) {
    return true ? constexpr_func() : throw strlen_runtime_error;
}

我很好奇,如果它有任何使用的东西,但我自己找不到任何有用的东西。外部错误是未定义的。

1 个答案:

答案 0 :(得分:1)

根据库中another of the functions的评论,它似乎试图强制执行仅在编译时使用的函数:

// convenience function for inferring the string size and ensuring no
// accidental runtime encryption
template <uint64_t S, size_t N>
constexpr encrypted_string<S, N> make_encrypted_string(const char(&s)[N])
{
  return true ? encrypted_string<S, N>(s) :
    throw err::strenc_runtime_error;
}

然而,正如你所指出的,它在这里没有做任何事情。通常,constexpr函数中使用三元运算符的技巧用于在给定条件的情况下触发编译时错误 - 不确保对函数的所有调用都是常量表达式。有关该模式的说明,请参阅constexpr error at compile-time, but no overhead at run-time

如果您需要确保在编译期间找到结果,您可以轻松地将结果分配给constexpr变量:

constexpr int result = strlen("asd");