c++ - 元编程 : using a const array

标签 c++ constants metaprogramming template-meta-programming

我是元编程的新手,在使用选项卡时遇到与 const 相关的问题。

假设我们有几种“类型”。每种类型都有不同的版本,我们将能够处理每种类型的所有版本。为此,我们使用一个包含有关类型的标准信息的结构,以及一个包含每个版本信息的数组。

问题是,每种类型的版本数量都不相同。此外,版本号不是很高,所以我不喜欢使用上述表的动态分配。但是如果我做静态分配,我需要为结构的每个实例有一个相同大小的表。这意味着,我必须获得最高版本值并将其用作数组的大小。

我来了:我想创建一个小型元编程模板,它在编译时提供最高版本值,这样我就可以拥有一个固定大小的数组,它肯定会包含每种类型的必要信息。但是我得到一个编译错误。

这是重现问题的简化示例代码(错误随之而来)

#include <stdio.h>

// change values here
#define VERSION_ALPHA 3
#define VERSION_BETA 5
#define VERSION_GAMMA 2

// different available types
enum TYPES
{
    T_ALPHA = 0,
    T_BETA,
    T_GAMMA,

    T_COUNT, // number of types
};

// to access versions more easily from code
static const int typeVersions[T_COUNT] =
{
    VERSION_ALPHA,
    VERSION_BETA,
    VERSION_GAMMA
};

// this meta is used to get the highest version values between all types
template<int i>
class HighestVersion
{
private:
    // version of type -1
    enum
    {
        PREVIOUS = HighestVersion<i-1>::VALUE
    };

public:
    // current max value
    enum
    {
        VALUE = (typeVersions[i] > PREVIOUS ? typeVersions[i] : PREVIOUS)
    };
};

// first version
template<>
class HighestVersion<0>
{
public:
    // current max value
    enum
    {
        VALUE = typeVersions[0]
    };
};

// highest version macro
#define HIGHEST_VERSION HighestVersion<T_COUNT>::VALUE

// holds info about a single type
struct TypeInfo
{
    char * s_pName; // name of the type as string
    unsigned int s_Flags[HIGHEST_VERSION]; // flags for each available version of this type
};


int main()
{
    // instanciate
    TypeInfo infos[T_COUNT];

    // do stuff, set name, load flags....
    /*...*/

    // for test purpose, print max version value (should print 5 in this situation)
    printf("%d\n", HIGHEST_VERSION);
}

编译器说:

error C2057: expected constant expression

@线条

VALUE = (typeVersions[i] > PREVIOUS ? typeVersions[i] : PREVIOUS)

VALUE = typeVersions[0]

编译器似乎告诉我表的内容不是常量。我认为这是因为该表被解释为一个指针,在这种情况下它不是常量(因此,如果指针更改,内容就不一样了)。有没有办法更正它以便我可以使用该脚本?这将使用户不​​需要手动设置该表的大小...

提前致谢:)

最佳答案

我敢肯定它甚至不可能用静态数组来实现。
一个可能的替代方案是特征类:

template<TYPES>
struct typeVersions;

// specializations for each type

template<>
struct typeVersions<T_ALPHA> { static const int version = VERSION_ALPHA; };
template<>
struct typeVersions<T_BETA> { static const int version = VERSION_BETA; };
// etc...

你会像这样使用它:

enum {
    VALUE = typeVersions<i>::version
};

关于c++ - 元编程 : using a const array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17834687/

相关文章:

python - Boost.Python TypeError : __init__() should return None not 'NoneType' - but no obvious linker or version problem

c++ - 动态库中的 libstdc++ 静态链接

c++ - 为什么 std::numeric_limits<T>::max() 是一个函数?

c# - 私有(private)常量与公共(public)只读

constants - MQL4 - 如何在 MQL4 脚本中将 "today"-datetime 设置为外部变量?

c++ - 在 C++14 中使用 hana::transform 转换元组内部的类型

c++ - 如何使用 BOOST BinaryFunction 概念?

c++ - 使用 range-v3 读取以逗号分隔的数据行

c++ - ppl 中的任务执行属性

ruby - 在模块上下文中向基类添加方法