class 模板的 constexpr 运算符重载
constexpr operator overloading of class templates
我正在使用模板元编程技术,目前我只是在尝试不同的做事方法。这是代码:
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 更正。
我正在使用模板元编程技术,目前我只是在尝试不同的做事方法。这是代码:
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 更正。