c++ - 类模板的 constexpr 运算符重载

标签 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

有人能帮我弄清楚为什么吗?谢谢。

最佳答案

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

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

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

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

关于c++ - 类模板的 constexpr 运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51727179/

相关文章:

c++ - 在 C++ 中,我是否需要在关闭程序之前释放内存

c++ - 处理运行时类型未知的模板

c++ - 如何将 N 个整数读入 vector ?

c++ - clock_nanosleep - 请求和保留的相同指针?

c++ - 对象仍在范围内时调用 Arduino 类析构函数

c++ - `weak_ptr::expired` 对象 dtor 中的行为

c++ - 在 MSVC++14 上的 C++11 中难以置信的快速委托(delegate)

c++ - 读取存储在多重映射中的私有(private)枚举作为值

c++ - 在C++中使循环变量成为常量

c++ - 具有可变模板参数的函数指针