【问题标题】:Variadic template doesn't recognise a constexpr function可变参数模板无法识别 constexpr 函数
【发布时间】:2013-07-10 19:03:42
【问题描述】:

我正在尝试在编译时初始化一些 C++ 数组,但我遇到了一个奇怪的 g++ 错误。这是我能得到的最小的代码块,它重现了错误:

#include <array>

template<typename Ar, int... Vals>
constexpr Ar Map(typename Ar::value_type /*int*/ fun(int)) 
{ return {{ fun(Vals)... }}; }

constexpr int add(int i) { return i + 1; }

constexpr auto b = Map<std::array<int, 2>, 1, 2>(add);

编译器在抱怨

bug.cpp:8:53:   in constexpr expansion of ‘Map<std::array<int, 2ul>, {1, 2}>(add)’
bug.cpp:4:80: error: expression ‘add’ does not designate a constexpr function
 constexpr Ar Map(typename Ar::value_type /*int*/ fun(int)) { return {{ fun(Vals)... }}; }

g++ 4.7.1 和 4.9.0 20130520(实验性)都会发生这种情况。注意 如果我在定义中将typename Ar::value_type 替换为int(见评论) Map,一切正常。这是我做错了什么的错误吗?

【问题讨论】:

    标签: c++ c++11 variadic-templates type-safety constexpr


    【解决方案1】:

    【讨论】:

    • typename Ar::value_type 被替换为int 时,它确实可以编译
    • @mirk:阅读错误报告:The template parameter in your example has similar effects as a typedef. Both use cases should not invalidate the constexpr character.typedef 或模板参数一起使用时会发生这种情况。
    • 感谢您的回答!调试这些代码仍然是一场噩梦。
    猜你喜欢
    • 2020-02-13
    • 2021-11-28
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多