constexpr 静态成员变量的链接器错误
Linker error with constexpr static member variable
如果能解释一下为什么以下代码会产生编译错误,我将不胜感激:
undefined reference to sinet::testtable'
这是实际的代码:
#define TABLE_SIZE 2000
template<class Function, std::size_t... Indices>
constexpr static auto make_array_helper(Function f, std::index_sequence<Indices...>)
-> std::array<typename std::result_of<Function(std::size_t)>::type, sizeof...(Indices)>
{
return {{ f(Indices)... }};
}
template<int N, class Function>
constexpr static auto make_array(Function f)
-> std::array<typename std::result_of<Function(std::size_t)>::type, N>
{
return make_array_helper(f, std::make_index_sequence<N>{});
}
constexpr static float fun(double x) { return (float)sin(((double)x / (double)TABLE_SIZE) * M_PI * 2.0); }
class sinet{
public:
constexpr static auto testtable = make_array<TABLE_SIZE>(fun);
};
代码应该在编译时填充静态数组,只要 constexpr static array
不是成员,它就可以工作。
如果我将静态成员初始化为单个浮点数,它就可以工作,因为没有链接器错误。但为什么?
有很多与此类似的问题,但我无法辨别特定于我的示例的答案。
如有任何帮助,我们将不胜感激。
编辑:
感谢 djrollins 的回答,我现在知道静态成员不能被评估为 constexpr 因为 sin 也不能。
这很不幸,因为这一切都是为了在编译时初始化一个静态数组,但似乎这是不可能的。
constexpr static
成员只能在 class 体内初始化,如果初始化器也是 constexpr
.
您的 fun
函数包含对 sin
的调用,与大多数标准数学函数一样,它不是 constexpr
.
如果能解释一下为什么以下代码会产生编译错误,我将不胜感激:
undefined reference to sinet::testtable'
这是实际的代码:
#define TABLE_SIZE 2000
template<class Function, std::size_t... Indices>
constexpr static auto make_array_helper(Function f, std::index_sequence<Indices...>)
-> std::array<typename std::result_of<Function(std::size_t)>::type, sizeof...(Indices)>
{
return {{ f(Indices)... }};
}
template<int N, class Function>
constexpr static auto make_array(Function f)
-> std::array<typename std::result_of<Function(std::size_t)>::type, N>
{
return make_array_helper(f, std::make_index_sequence<N>{});
}
constexpr static float fun(double x) { return (float)sin(((double)x / (double)TABLE_SIZE) * M_PI * 2.0); }
class sinet{
public:
constexpr static auto testtable = make_array<TABLE_SIZE>(fun);
};
代码应该在编译时填充静态数组,只要 constexpr static array
不是成员,它就可以工作。
如果我将静态成员初始化为单个浮点数,它就可以工作,因为没有链接器错误。但为什么?
有很多与此类似的问题,但我无法辨别特定于我的示例的答案。
如有任何帮助,我们将不胜感激。
编辑:
感谢 djrollins 的回答,我现在知道静态成员不能被评估为 constexpr 因为 sin 也不能。
这很不幸,因为这一切都是为了在编译时初始化一个静态数组,但似乎这是不可能的。
constexpr static
成员只能在 class 体内初始化,如果初始化器也是 constexpr
.
您的 fun
函数包含对 sin
的调用,与大多数标准数学函数一样,它不是 constexpr
.