我想要一个constexpr从constexpr函数计算的值(即编译时常量).我想要将这两个作用于类的命名空间,即静态方法和类的静态成员.
我第一次写这个(对我来说)明显的方式:
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++代码,为什么不呢?
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) 任何人都可以试着解释一下吗?
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) 我正在尝试实现以下内容:
#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.有任何想法吗?