-1

I have a simple struct:

struct Test
{
    int a;

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

I need to declare CT TransformData variable. It works with #define:

#define testDefault = Test(1, 2)

But I need to separate this variable to a separate namespace. If I use consexpr I get the error:

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

I've googled about constexpr and seems constexpr limits don't allow declare such class instance as constexpr. Which are there ways to declare such constant?

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
Wusiki Jeronii
  • 159
  • 1
  • 8

1 Answers1

2

The class you show is actually a good candidate for producing constexpr constants. But its constructor needs to be marked 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" is a normative term for types that can produce constant expressions. Your compiler was telling you that one of the requirements is missing.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • What about more difficult classes? struct Test was just an example. https://pastebin.com/sjAh9sKN. There is a more difficult struct here. A constructor has ~ 115 code lines. Need to describe all lines twice? Declaring a function for constructor? What is the best way to do that? – Wusiki Jeronii Sep 12 '21 at 21:48
  • `constexpr` code has some limitation. You need to start with simple cases to understand when it can be used. At first, I would not expect such large constructor to be a good candidate for `constexpr`. – Phil1970 Sep 12 '21 at 22:01