相关疑难解决方法(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万
查看次数

静态模板化constexpr嵌套类成员

我有以下Foo带嵌套类的示例类Bar,一切都是constexpr:

class Foo
{
private:
    template <typename T>
    struct Bar
    {
        constexpr Bar(){}
        constexpr int DoTheThing() const
        {
            return 1;
        }
    };

public:
    constexpr static auto b = Bar<int>{};
    constexpr Foo() {}
    constexpr int DoTheThing() const
    {
        return b.DoTheThing();
    }
};
Run Code Online (Sandbox Code Playgroud)

我想测试那个调用Foo::DoTheThing返回1:

int main()
{
   constexpr Foo f;
   static_assert(f.DoTheThing() == 1, "DoTheThing() should return 1");
}
Run Code Online (Sandbox Code Playgroud)

GCC和Clang都在这里抱怨,但MSVC没有

GCC说:

错误:constexpr Foo::Bar<T>::Bar() [with T = int]在定义之前使用

constexpr static auto b = …
Run Code Online (Sandbox Code Playgroud)

c++ templates language-lawyer constexpr c++14

13
推荐指数
1
解决办法
551
查看次数

内部类的奇怪constexpr行为

任何人都可以试着解释一下吗?

template<typename T, size_t S = T::noElems()>
struct C
{
};

struct X
{
    enum E { A, B, C };
    static constexpr size_t noElems() { return C+1; };
};

struct K
{
    C<X> cx; // this DOES compile
};

struct Y
{
    struct Z
    {
        enum E { A, B, C };
        static constexpr size_t noElems() { return C+1; };
    };
    C<Z, Z::C+1> cyz; // this DOES compile

    C<Z> cyz; // <--- this does NOT compile 
};
Run Code Online (Sandbox Code Playgroud)

c++ constexpr c++11

10
推荐指数
1
解决办法
297
查看次数

标签 统计

c++ ×3

constexpr ×3

c++11 ×1

c++14 ×1

g++ ×1

gcc ×1

language-lawyer ×1

static-members ×1

templates ×1