相关疑难解决方法(0)

constexpr使用静态函数初始化静态成员

要求

我想要一个constexprconstexpr函数计算的值(即编译时常量).我想要将这两个作用于类的命名空间,即静态方法和类的静态成员.

第一次尝试

我第一次写这个(对我来说)明显的方式:

class C1 {
  constexpr static int foo(int x) { return x + 1; }
  constexpr static int bar = foo(sizeof(int));
};
Run Code Online (Sandbox Code Playgroud)

g++-4.5.3 -std=gnu++0x 对此说:

error: ‘static int C1::foo(int)’ cannot appear in a constant-expression
error: a function call cannot appear in a constant-expression
Run Code Online (Sandbox Code Playgroud)

g++-4.6.3 -std=gnu++0x 抱怨:

error: field initializer is not constant
Run Code Online (Sandbox Code Playgroud)

第二次尝试

好吧,我想,也许我必须把事情从课堂上移开.所以我尝试了以下方法:

class C2 {
  constexpr static int foo(int x) { return x + 1; }
  constexpr static int bar;
}; …
Run Code Online (Sandbox Code Playgroud)

c++ gcc g++ static-members constexpr

31
推荐指数
2
解决办法
3万
查看次数

在C++ 14中扣除'auto'之前使用'auto func(int)'

我在GCC中编译了以下程序C++14.

#include <iostream>
using namespace std;

auto func(int i);

int main() 
{
    auto ret = func(5);
    return 0;
}

auto func(int i) 
{
  if (i == 1)
    return i;              
  else
    return func(i-1) + i;  
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误.

In function 'int main()': 8:16: error: use of 'auto func(int)' before
deduction of 'auto'
 auto ret = func(5);
Run Code Online (Sandbox Code Playgroud)

那么,我在这里错过了什么?

c++ gcc function auto c++14

24
推荐指数
3
解决办法
9441
查看次数

静态 constexpr 成员变量初始化

我有以下代码:

struct Foo
{       
    struct Bar
    {
        std::uint32_t x = -1;

        constexpr Bar(std::uint32_t x) : x(x) {}
    };

    static constexpr Bar CONST_BAR = Bar(0);
};
Run Code Online (Sandbox Code Playgroud)

当我尝试编译它时,出现以下错误:

错误:'constexpr Foo::Bar::Bar(uint32_t)' 在定义完成之前在常量表达式中调用

有人可以向我解释发生了什么吗?据我所知,Bar 的构造函数是在第一次调用之前定义的。

活生生的例子

c++ constexpr c++14

12
推荐指数
1
解决办法
231
查看次数

N3936的3.3.7/1节中的规则3是多余的吗?

我最近回答了一个涉及违反C++ 14标准草案的问题:N4140部分3.3.7 类范围段落1规则2说:

在类S中使用的名称N应在其上下文中引用相同的声明,并在完成的S范围内重新评估.违反此规则不需要诊断.

当时的规则3似乎也很重要,它说:

如果类中的重新排序成员声明在(1)和(2)下产生备用有效程序,则程序格式错误,不需要诊断.

我最初的反应是,规则3似乎是多余的,实际上只是对规则的澄清,2并不涵盖任何尚未涵盖的案例.导致备用有效程序的重新排序也必须违反规则2.

那么规则是3多余的还是有一些边缘情况需要两个规则?

c++ scope language-lawyer c++14

6
推荐指数
1
解决办法
761
查看次数

标签 统计

c++ ×4

c++14 ×3

constexpr ×2

gcc ×2

auto ×1

function ×1

g++ ×1

language-lawyer ×1

scope ×1

static-members ×1