在constexpr使用boost数学常数 [英] using boost math constants in constexpr
问题描述
时,可以在constexpr使用boost数学常数?
Is is possible to use boost math constants in constexpr?
例如,下面一行:
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
但是,如果我更换增压code。与简单M_PI,它工作正常。
But if I replace the boost code with simple M_PI, it works fine.
推荐答案
我怀疑这可能是原因。 Coliru 给出了这样的错误:
I suspect this may be the reason. Coliru gives this error:
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; } \
如果它被定义为常量
,而不是 constexpr
,这可能是为什么它拒绝code。为了安慰自己,这是问题的根源,我们可以重现错误与此测试用例:
If it's defined as const
and not constexpr
, that may be why it's rejecting the code. To reassure ourselves that is the source of the issue, we can reproduce the error with this testcase:
// 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;
那么,我们如何解决这个问题?不要使用非模板版本。升压提供href=\"http://www.boost.org/doc/libs/1_55_0/libs/math/doc/html/math_toolkit/tutorial/templ.html\" rel=\"nofollow\">模板版本,我们可以用代替。
So how do we fix this? Don't use the non-templated version. Boost provides a templated version that we can use instead.
static constexpr double SEC3 = static_cast<double>(45)/180*boost::math::constants::pi<double>();
铛3.5还实现了与C ++ 1Y模式变量模板:
clang 3.5 also implements variable templates with C++1y mode:
template <class T>
static constexpr T SEC3 = static_cast<T>(45)/180*boost::math::constants::pi<T>();
int main()
{
std::cout << SEC3<double>;
}
这篇关于在constexpr使用boost数学常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!