在C ++中初始化类的静态数组成员的更好方法(尽管首选const) [英] A better way to initialize a static array member of a class in C++ ( const would be preferred though )

查看:259
本文介绍了在C ++中初始化类的静态数组成员的更好方法(尽管首选const)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态的指向函数的指针数组,该指针作为类的成员.

I have a static array of pointers to functions as a member of a class.

我需要对其进行初始化,但事实证明此数组的长度为64K,因此使用像{ x, y, z, ... }这样的静态初始化程序进行初始化是不切实际的,因为这样会使代码混乱.

I need to initialize it, but it turns out this array is 64K items long, so it's impractical to initialize it with a static initializer like { x, y, z, ... } as it would clutter code.

我必须通过几个循环的代码来初始化它.

I have instead to initialize it by code, with several loops.

我想到的方法是通过在构造函数中初始化static数组并为其设置一个标志,因此只有构造该类的第一个实例时才会触发该初始化.

The way I figured to do this is by initializing the static array in the constructor and setting a flag to it, so only the construction of the first instance of the class would fire this initialization.

从实例内部访问此静态标志也不是线程安全的,但这是另一回事了.

Also accessing this static flag from within instances would not be thread safe, but that's another story.

是否有更清洁或更完善的方法?

Is there a cleaner or better way of doing this?

我也希望此数组为const,但是恐怕唯一的方法是使用static {}初始化,对吧?

I also would like this array to be const, but I'm afraid the only way to do it is with the static {} initialization, right?

推荐答案

另一种选择是使用代码生成:编写一个单独的程序,为静态数组的定义生成源代码.

Another option would be to use code generation: Write a separate program that generates the source code for the definition of the static array.

这篇关于在C ++中初始化类的静态数组成员的更好方法(尽管首选const)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆