我正在使用模板元编程技术,目前我只是在尝试不同的做事方法。这是代码:
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/