CT class 实例,在单独的命名空间中具有非文字变量

CT class instance with non-literal variables in separate namespace

我有一个简单的结构:

struct Test
{
    int a;

    Test(int b, int c)
    {
        a = b * c;
    }
};

我需要声明 CT TransformData 变量。它适用于 #define:

#define testDefault = Test(1, 2)

但是我需要将这个变量分离到一个单独的命名空间。如果我使用 consexpr 我得到错误:

the type «const Test» of «constexpr» variable «test» is not literal

我在谷歌上搜索了 constexpr,似乎 constexpr 限制不允许将此类 class 实例声明为 constexpr。 有哪些方法可以声明这样的常量?

您展示的 class 实际上是生成 constexpr 常量的一个很好的候选者。但是它的构造函数需要标记为constexpr.

struct Test
{
    int a;

    constexpr Test(int b, int c)
       : a(b*c) // must be initialized up to C++20
    {
        a = b * c + 1; // but can still be reassigned
    }
};

A "literal type" 是可以产生常量表达式的类型的规范术语。您的编译器告诉您缺少其中一项要求。