简体   繁体   中英

Can I get a C++ Compiler to instantiate objects at compile time?

I am writing some code that has a very large number of reasonably simple objects and I would like them the be created at compile time. I would think that a compiler would be able to do this, but I have not been able to figure out how.

In C I could do the the following:

#include <stdio.h>

typedef struct data_s {
    int a;
    int b;
    char *c;
} info;

info list[] = {
    1, 2, "a",
    3, 4, "b",
};

main()
{
   int i;
   for (i = 0; i < sizeof(list)/sizeof(*list); i++) {
     printf("%d %s\n", i, list[i].c);
   }
}

Using #C++* each object has it constructor called rather than just being layed out in memory.

#include <iostream>
using std::cout;
using std::endl;

class Info {
    const int a;
    const int b;
    const char *c;
public:
    Info(const int, const int, const char *);
    const int get_a() { return a; };
    const int get_b() { return b; };
    const char *get_c() const { return c; };
};

Info::Info(const int a, const int b, const char *c) : a(a), b(b), c(c) {};

Info list[] = {
    Info(1, 2, "a"),
    Info(3, 4, "b"),
};

main()
{
    for (int i = 0; i < sizeof(list)/sizeof(*list); i++) {
        cout << i << " " << list[i].get_c() << endl;
    }
}

I just don't see what information is not available for the compiler to completely instantiate these objects at compile time, so I assume I am missing something.

In C++ 2011 you can create objects at compile time. For this to happen, you need to make various things constant expressions, however:

  1. The constructor needs to be declared constexpr .
  2. The entity you declare needs to be declared constexpr .

Note, that nearly all your const qualifiers are either irrelevant or in the wrong location. Here is an example with the various correction and also actually demonstrating that the list array is initialized during compile time (by using members of it to define the values of an enum ):

#include <iostream>
#include <iterator>

class Info {
    int a;
    int b;
    char const*c;

public:
    constexpr Info(int, int, char const*);
    constexpr int get_a() const { return a; }
    constexpr int get_b() const { return b; }
    constexpr char const*get_c() const { return c; }
};

constexpr Info::Info(int a, int b, char const*c)
  : a(a), b(b), c(c) {}

constexpr Info list[] = {
    Info(1, 2, "a"),
    Info(3, 4, "b"),
};

enum {
    b0 = list[0].get_b(),
    b1 = list[1].get_b()
};

int main()
{
    std::cout << "b0=" << b0 << " b1=" << b1 << "\n";
    for (Info const* it(list), *end(list); it != end; ++it) {
        std::cout << (it - list) << " " << it->get_c() << "\n";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM