【问题标题】:Can I get a C++ Compiler to instantiate objects at compile time?我可以让 C++ 编译器在编译时实例化对象吗?
【发布时间】:2012-09-17 05:37:17
【问题描述】:

我正在编写一些代码,其中包含大量相当简单的对象,我希望在编译时创建它们。我认为编译器能够做到这一点,但我无法弄清楚如何。

在 C 中,我可以执行以下操作:

#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);
   }
}

使用#C++* 每个对象都有它的构造函数被调用,而不是仅仅被放置在内存中。

#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;
    }
}

我只是看不到编译器无法在编译时完全实例化这些对象的信息,所以我认为我遗漏了一些东西。

【问题讨论】:

  • 看看静态类或单例 idom。也许这就是你在 c++ 中寻找的东西
  • the same question on Programmers 的答案有什么问题?
  • @Najzero C++ 没有静态类。
  • @DCoder:我对你的问题的回答是:“没有提到 C++ 的方法”。当然,这假设作者打错了标题,这很可能是因为实际问题显然使用的是 C++ 而不是 C。

标签: c++ optimization gcc


【解决方案1】:

在 C++ 2011 中,您可以在编译时创建对象。为此,您需要将各种事物设为常量表达式,但是:

  1. 构造函数需要声明constexpr。
  2. 您声明的实体需要声明为constexpr。

请注意,几乎所有 const 限定符要么不相关,要么位置错误。这是一个带有各种更正的示例,实际上也证明了 list 数组在编译期间被初始化(通过使用它的成员来定义 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";
    }
}

【讨论】:

  • a 和 b 不是必须是 const 才能使 constexpr get_a 合法吗?或者 constexpr 对象是否可以修改(我知道它们是私有的,但是如果我在 Info 对象上分配给 a 会发生什么?
  • @ted:成员不必是constexpr,因为整个对象是constexpr。如果您想从非const 对象中获取constexpr,但要访问该成员必须是constexpr 的成员(当然,还有定义该成员的各种其他内容)。
  • 感谢您的解释。你的意思是 by 你写了 but 的地方吗?
  • 呃,是的:应该是 by 的。
猜你喜欢
  • 2019-11-01
  • 2011-05-25
  • 2018-07-08
  • 2014-01-16
  • 1970-01-01
  • 2017-03-15
  • 1970-01-01
  • 1970-01-01
  • 2011-01-11
相关资源
最近更新 更多