首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当使用模板时,Constexpr函数不是constexpr函数。

当使用模板时,Constexpr函数不是constexpr函数。
EN

Stack Overflow用户
提问于 2019-02-02 21:55:24
回答 1查看 74关注 0票数 2

以下代码编译得很好:

代码语言:javascript
复制
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;
}

但是,如果我们将模板类型参数T添加到A中,

代码语言:javascript
复制
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‘不能导致常量表达式“。

这怎麽可能?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-02 22:07:36

是的,MSVC在C++14/17特性的实现上有(或仍然存在)一些问题,这显然也适用于constexpr。但是,在Visual 2017 15.9中,以下轻微的修改对我来说是有效的(而OP中的版本也会出现错误):

代码语言:javascript
复制
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>{};
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54497908

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档