0

I am working with template meta programming techniques, and I'm just playing around with different methods of doing things at the moment. Here is the code:

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;
}

When I try to run this, it gives me this error message:

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

Can someone help me figure out why? Thanks.

1 Answer 1

1

I don't see problems in your code and it compiles without problems with my clang++ 3.8.1.

But I have your same error with my g++ 6.3.0.

Trying with newer versions of g++ (starting from g++ 7.1.0) the error disappear.

So I suppose that the error is a bug in olds versions of g++, corrected from g++ 7.1.0.

Sign up to request clarification or add additional context in comments.

2 Comments

I am observing the same behavior of g++ 6.3.0. Interestingly, the error message disappears after explicitly defaulting the constructor iwrapper() = default;. Alternatively, passing the arguments to operator+ by value helps, too.
The error also goes away by using constexpr iwrapper<2> first{}; i.e. changing first to first{}. Might be related to this GCC bug

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.