sizeof(...) = 0 或 c++ 中的条件变量声明模板
假设我有这样的东西:
struct EmptyClass{};
template<typename T1, typename T2 = EmptyClass,
typename T3 = EmptyClass, typename T4 = EmptyClass,
..., typename T20> class PoorMansTuple {
T1 t1;
T2 t2;
...
T20 t20;
};
现在,每个 PoorMansTuple 可能会浪费多达 19 个字节。
问题是:
1)有没有办法创建一个大小为0的类?
2)有没有办法有条件地定义变量?比如:
T1 t1;
if (T2 != EmptyClass) T2 t2; // pseudo code
if (T3 != EmptyClass) T3 t3; // ...
谢谢!
允许使用黑魔法宏。
我在 MacOSX 上使用 g++。
Suppose I have something like this:
struct EmptyClass{};
template<typename T1, typename T2 = EmptyClass,
typename T3 = EmptyClass, typename T4 = EmptyClass,
..., typename T20> class PoorMansTuple {
T1 t1;
T2 t2;
...
T20 t20;
};
Now, I may waste up to 19bytes per PoorMansTuple.
Question is:
1) Is there a way to create a class of size 0?
2) Is there a way to conditionally define a varaible? Somethign like:
T1 t1;
if (T2 != EmptyClass) T2 t2; // pseudo code
if (T3 != EmptyClass) T3 t3; // ...
Thanks!
The use of black magic macros is premitted.
I'm using g++ on MacOSX.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
部分专业化可能是您正在寻找问题的第一部分。该程序
打印
Partial specialization may be what you are looking for the first part of the question. This program
prints
1)不,因为类的实例不能有内存地址。地址至少需要 1 个字节。 ——也就是说,没有任何实例和直接引用(例如仅在模板生成时使用)的类将没有大小,因为它不在编译的程序中。
2) 不是没有宏...或者可能是只有 boost.org 忍者才能掌握的晦涩模板黑魔法。我听说过编译时“if”的想法,但目前它还没有出现在任何即将推出的语言标准中。那会允许的。正如已经说过的,也许有一个技巧可以做到。
1) No, because the instance of the class couldn't have a memory adress. It requires at least 1 byte to have an adress. -- that said, a class that don't have any instance and direct reference (used only at template generation for example) will have no size as it not be in the compiled program.
2) Not without macro...or maybe obscure template black arts that only boost.org ninjas can master. I've heard of the idea of compile-time "if" but it's not currently in any coming standard of the language AFAIK. That would have allowed it. As already said, maybe there is a trick to make it.
查看
boost::tuple
和boost::compressed_pair
。类的大小不能为 0,但存在“空基类”优化的概念。呃,我只想链接到我之前的一个答案,在我看来,它在这里非常相关: 什么是 std::pair?Check out
boost::tuple
andboost::compressed_pair
. A class can't have a sizeof 0, but there is the concept of the "empty base class" optimization. Eh, I'm just going to link to one of my previous answers, it is pretty relevant here IMO: What is std::pair?