constexpr运算符重载类模板

时间:2018-08-07 12:46:10

标签: c++ c++11 templates template-meta-programming constexpr

我正在使用模板元编程技术,而现在我只是在玩不同的做事方法。这是代码:

template<const int A>
struct iwrapper
{
    static const int num = A;
};

template<int A, int B>
constexpr iwrapper<A+B> operator+(iwrapper<A>, iwrapper<B>)
{
    return iwrapper<iwrapper<A>::num + iwrapper<B>::num>();
}

int main()
{
    constexpr iwrapper<2> first;
    constexpr iwrapper<4> second;

    constexpr auto answer = first + second;
}

当我尝试运行此命令时,它会显示以下错误消息:

error: the value of 'first' is not usable in a constant expression

有人可以帮我找出原因吗?谢谢。

1 个答案:

答案 0 :(得分:1)

我在您的代码中看不到问题,并且在我的clang ++ 3.8.1中也可以正常编译。

但是我的g ++ 6.3.0也有同样的错误。

尝试使用较新版本的g ++(从g ++ 7.1.0开始),错误消失。

所以我认为该错误是旧版本的g ++中的错误,已从g ++ 7.1.0中更正。