2
votes

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?

1
Which compiler? On Coliru, it compiles fine. - davidhigh
Compiler: Microsoft visual C++ 14.16.27023 - Carucel

1 Answers

2
votes

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