假设我有这样的东西:
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++。
最佳答案
Partial specialization 可能是你要找的问题的第一部分。这个程序
#include <string>
#include <iostream>
struct EmptyClass {};
template<typename T1, typename T2>
class Tuple
{
T1 t1;
T2 t2;
};
template<typename T1>
class Tuple <T1, EmptyClass>
{
T1 t1;
};
int main (void)
{
Tuple<std::string, std::string> two;
Tuple<std::string, EmptyClass> one1;
Tuple<std::string> one2;
std::cout << "<string, string>: " << sizeof(two) << std::endl;
std::cout << "<string, empty> : " << sizeof(one1) << std::endl;
std::cout << "<string> : " << sizeof(one2) << std::endl;
return 0;
}
打印
<string, string>: 32
<string, empty> : 16
<string> : 16
关于c++ - sizeof(...) = 0 或 C++ 模板中的条件变量声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2293231/