如何初始化类中的数组,该类的值可以在常量表达式中使用
How to initialize an array in a class whose values can be used in constant-expressions?
我想知道如何初始化类中的数组,该类的值可以在常量表达式中使用。以下是对我的问题的解释:
// The goal : initializing an array for a class
// whose values can be used as normal static const
// (as template parameters for example)
class MyClass
{
public:
static const unsigned int value = 42; // <- No problem here
static const unsigned int array[3] = {100, 101, 102}; // <- How to initialize this static const array (with constexpr or metaprogrammation maybe ?)
template<unsigned int T> inline void f() {std::cout<<"Hello, my value is "<<T<<std::endl;} // <- Simple function for demonstration purposes
inline void fvalue() {f<value>();} // <- No problem here
inline void farray() {f<array[1]>();} // <- Big problem here
};
//const unsigned int Class1::array[3] = {100, 101, 102}; // <- If I do this, I will initialize the array but farray() will not compile
在C++2011中有什么方法可以做到这一点吗?(可能有constexpr或元编程?)
非常感谢!
EDIT:正如标题所指定的,我需要array
作为类的成员(而不是全局数组)。
是的,您可以将其设为constexpr
。。
当静态成员在类中初始化时,使其成为constexpr
可以使其具有比积分或枚举类型更多的类型。特别是,成员只需要是文字类型,初始化器中的所有表达式都必须是常量表达式。所以这是很好的
class MyClass
{
public:
static constexpr unsigned int array[3] = {100, 101, 102};
template<unsigned int T> inline void f() {
std::cout<<"Hello, my value is "<<T<<std::endl;
} // <- Simple function for demonstration purposes
inline void farray() {f<array[1]>();}
};
// needs a definition out-of-class too. put it into a .cc file
constexpr unsigned int MyClass::array[3];
如果您想知道元编程示例会是什么样子,下面是一个示例:
#include <iostream>
template<size_t... values>
struct number_list;
template<size_t value, size_t... values>
struct number_list<value, values...>
{
static const size_t val = value;
typedef number_list<values...> next;
};
template<size_t index, typename NumList>
struct indexer
{
static const size_t val = indexer<index - 1, typename NumList::next>::val;
};
template<typename NumList>
struct indexer<0, NumList>
{
static const size_t val = NumList::val;
};
template<typename NumList>
class MyClass
{
public:
template<size_t T> inline void f()
{
std::cout << "Hello, my value is " << T << std::endl;
}
inline void farray() {f<indexer<1, NumList>::val>();}
};
int main()
{
MyClass<number_list<3, 5, 6>> a;
a.farray();
return 0;
}
相关文章:
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- 使用自动推导的 lambda 参数作为常量表达式
- 生成提升::hana::set 的常量表达式问题
- 为什么不能用常量表达式声明数组?
- 不是 lambda 函数中的常量表达式
- 函数调用在常量表达式中必须具有常量值
- 错误:constexpr 变量'struct2Var'必须由常量表达式初始化
- 关于在需要常量表达式的上下文中使用的glvalue常量表达式的问题
- 生成 constexpr 字符串表,不能产生常量表达式
- 整体模板参数。错误:在常量表达式中使用'this'
- 如何在满足常量表达式的同时将整数传递给指针,传递给 std::array<double、integer>?
- 编译器错误:函数调用在常量表达式中必须有一个常量值
- 错误:'new'不能出现在常量表达式中
- 我可以写出小于 -0.5 两个 ulps 的常量表达式双精度吗?
- 编译器在传递 const 变量时返回错误:模板参数不是常量表达式
- 为什么我不能在非常量表达式上使用此模板阶乘函数?
- C++ 使用变量而不是常量表达式初始化数组
- 使用函数参数作为常量表达式的一部分 - gcc vs clang
- 片段着色器中的"错误:在 GLSL 1.30 及更高版本中禁止使用非常量表达式索引的采样器数组"