c++11 - 可选抛出constexpr吗?

标签 c++11 error-handling

当我发现某些代码中有异常的抛出模式时,我正在研究如何在此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/

相关文章:

c++ - 使用 ping 实用程序的 Qt QProccess

error-handling - Angular GlobalErrorHandler和HttpErrorResponse-解析器抛出格式错误的HttpErrorResponse

c++ - C++中指向int的指针

c++ - 如何在 makefile 中包含 -std=c++11 和 -lpthread?

c++ - 基于范围的for循环对性能有好处吗?

c++ - 如果我想使用 std::shared_ptr,要包含哪个 header ?

c++ - 完美转发的身份功能

C++(.cpp 文件和 .h 文件。)拆分代码并添加一个函数,提取 - 容易吗?

python - 训练自己的数据集。 Mask_RCNN资源耗尽: OOM when allocating

mongodb - 您如何提取MongoError : E11000 duplicate key found?的错误消息