当我发现某些代码中有异常的抛出模式时,我正在研究如何在此repo https://github.com/elbeno/constexpr中为玩具项目实现复杂的编译时间。它似乎什么也没做,您为什么要这样做?
namespace err {
extern const char * strlen_runtime_error;
}
constexpr int strlen(const char * str) {
return true ? constexpr_func() : throw strlen_runtime_error;
}
我很好奇它有什么用,但我自己找不到有用的东西。外部错误未定义。
最佳答案
根据该库的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");
关于c++11 - 可选抛出constexpr吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50185555/