链接器错误与constexpr静态成员变量

时间:2016-10-08 21:50:59

标签: c++ templates static linker 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的回答,我现在知道静态的memeber无法被评估为constexpr,因为罪恶也不能。

这是不幸的,因为所有这些都是在编译时初始化静态数组,但似乎这是不可能的。

1 个答案:

答案 0 :(得分:2)

如果初始化程序也是constexpr static

constexpr成员只能在类正文中初始化。

您的fun函数包含对sin的调用,与大多数标准数学函数一样,它不是constexpr

相关问题