【问题标题】:constexpr operator overloading of class templates类模板的 constexpr 运算符重载
【发布时间】:2019-01-14 13:37:01
【问题描述】:

我正在使用模板元编程技术,目前我只是在玩弄不同的做事方法。代码如下:

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

有人可以帮我弄清楚原因吗?谢谢。

【问题讨论】:

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


    【解决方案1】:

    我在您的代码中没有发现问题,并且它在我的 clang++ 3.8.1 中编译时没有问题。

    但是我的 g++ 6.3.0 也出现了同样的错误。

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

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

    【讨论】:

    • 我正在观察 g++ 6.3.0 的相同行为。有趣的是,在显式默认构造函数iwrapper() = default; 后,错误消息消失了。或者,通过值将参数传递给 operator+ 也有帮助。
    • 使用constexpr iwrapper&lt;2&gt; first{}; 也可以消除错误,即将first 更改为first{}。可能与this GCC bug 有关
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 2016-04-21
    • 2011-04-30
    • 2013-03-24
    相关资源
    最近更新 更多