2

The following code compiles fine:

struct A {
    int i;
    constexpr A() : i(1) { }
    constexpr A(const A& that) : i(1) { }
};
constexpr auto func() {
    std::array<A, 3> result = {};
    return result;
}

However, if we add a template type parameter T to A,

template<typename T> struct A {
    int i;
    constexpr A() : i(1) { }
    constexpr A(const A<T>& that) : i(1) { }
};
constexpr auto func() {
    std::array<A<int>, 3> result = {};
    return result;
}

the compiler errors "constexpr function 'func' cannot result in a constant expression".

How is this possible?

2
  • 2
    Which compiler? On Coliru, it compiles fine. Commented Feb 2, 2019 at 21:58
  • Compiler: Microsoft visual C++ 14.16.27023 Commented Feb 2, 2019 at 21:58

1 Answer 1

2

Yes, MSVC had (or still has) some problems with the implementation of C++14/17 features, and that obviously also applies to constexpr. With Visual Studio 2017 15.9, however, the following slight modification works for me (whereas the version in the OP also gives an error):

template<typename T> struct A {
    int i;
    constexpr A() : i(1) { }
    constexpr A(const A<T>& that) : i(1) { }
};
constexpr auto func() {
    return std::array<A<int>, 3>{};
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Is this a bug in the MSVC compiler?
Yes, it's a bug. It's probably something related to the copy constructor or to copy(-list) initialization.

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.