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

在编译时获取std :: array中的元素数

以下是有效的C++代码,为什么不呢?

std::array<std::string, 42> a1;
std::array<int, a1.size()> a2;
Run Code Online (Sandbox Code Playgroud)

它不能在GCC 4.8中编译(在C++ 11模式下).有一个简单但不优雅的解决方法:

std::array<std::string, 42> a1;
std::array<int, sizeof(a1)/sizeof(a1[0])> a2;
Run Code Online (Sandbox Code Playgroud)

很明显,编译器可以计算出std :: array中的元素数量.为什么std :: array :: size()不是constexpr static函数?

编辑:我找到了另一种解决方法:

std::array<std::string, 42> a1;
std::array<int, std::tuple_size<decltype(a1)>::value> a2;
Run Code Online (Sandbox Code Playgroud)

c++

28
推荐指数
2
解决办法
8123
查看次数

内部类的奇怪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
查看次数

constexpr与std :: array - "非类型模板参数不是常量表达式"

我正在尝试实现以下内容:

#include <array>
#include <cstdint>

class Class2
{
};

class Class1
{
public:
    static constexpr uint8_t GetMax() { return 5; }
    static constexpr uint8_t GetMin() { return 0; }
    static constexpr uint8_t GetCount() { return GetMax() - GetMin() + 1; }

private:
    std::array<Class2, Class1::GetCount()> m_classes;
};
Run Code Online (Sandbox Code Playgroud)

但由于错误,我无法让它工作:

非类型模板参数不是常量表达式

我正在使用Xcode 5.0.有任何想法吗?

c++ templates clang constexpr c++11

8
推荐指数
1
解决办法
2990
查看次数

标签 统计

c++ ×4

constexpr ×3

c++11 ×2

clang ×1

g++ ×1

gcc ×1

static-members ×1

templates ×1