使用模板时Constexpr功能不constexpr

问题描述 投票:2回答:1

下面的代码编译罚款:

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

但是,如果我们添加一个模板类型参数TA

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

编译器的错误“constexpr函数‘FUNC’不能导致一个常量表达式”。

这怎么可能?

c++ templates constexpr
1个回答
2
投票

是的,MSVC拥有(或仍然有)一些问题的C ++十七分之十四功能的实现,这显然也适用于constexpr。与Visual Studio 2017年15.9,然而,以下略作修改对我的作品(而在OP的版本还提供了一个错误):

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>{};
}
© www.soinside.com 2019 - 2024. All rights reserved.