c++ - 在 constexpr 中使用 boost 数学常量

标签 c++ boost c++11 constexpr

是否可以在 constexpr 中使用 boost 数学常量?

例如,下面一行:

static constexpr double SEC3 = static_cast<double>(45)/180*boost::math::double_constants::pi;

给我错误

Error - constexpr variable 'SEC3' must be initialized by a constant expression

但如果我用简单的 M_PI 替换 boost 代码,它就可以正常工作。

最佳答案

我怀疑这可能是原因。 Coliru给出这个错误:

clang++ -std=c++1y -O2 -Wall -pedantic -pthread main.cpp && ./a.out

/usr/local/include/boost/math/constants/constants.hpp:248:52: note: expanded from macro 'BOOST_DEFINE_MATH_CONSTANT'

   namespace double_constants{ static const double name = x; } \

如果它被定义为 const 而不是 constexpr,这可能就是它拒绝代码的原因。为了让我们自己确信这是问题的根源,我们可以用这个测试用例重现错误:

// This code fails
#include <boost/math/constants/constants.hpp>
namespace double_constants{ static const double name = 25; }

static constexpr double SEC3 = static_cast<double>(45)/180*double_constants::name;

那么我们如何解决这个问题呢?不要使用 non-templated version . Boost 提供了一个 templated version我们可以改用它。

static constexpr double SEC3 = static_cast<double>(45)/180*boost::math::constants::pi<double>();

clang 3.5 还用 C++1y 模式实现了变量模板:

template <class T>
static constexpr T SEC3 = static_cast<T>(45)/180*boost::math::constants::pi<T>();

int main()
{
    std::cout << SEC3<double>;
}

关于c++ - 在 constexpr 中使用 boost 数学常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21688678/

相关文章:

c++ - 如何处理可能是 std::string 或 std::wstring 的值

visual-c++ - MSVC++ map<int, list<unique_ptr<test>>> 不编译引用已删除的函数

c++ - 创建boost::shared_ptr的深层拷贝

c++ - 模板参数未在此范围内声明

c++ - 使用 POSIX 从 SERIAL 也读取 null

c++ - 在不使用 std::map 的情况下从短语中计算单词的问题

c++ - 强制部分运营商成为成员(member)的理由

c++ - 如何在其他线程中运行 io_service?

c++ - boost 序列化 : Serializing a tree with root memory management

c++ - Boost UpgradeLockable概念