gpt4 book ai didi

C++元编程疯狂

转载 作者:搜寻专家 更新时间:2023-10-31 01:21:15 25 4
gpt4 key购买 nike

考虑以下模板化数据结构

enum eContent{
EINT = 1,
EFLOAT = 2,
EBOOL = 4
};

template<int>
struct Container{
Container(){assert(false);} //woops, don't do that!
};

template<>
struct Container<EINT>{
Container():i(123){}
int i;
};

template<>
struct Container<EFLOAT>{
Container():f(123.456f){}
float f;
};

template<>
struct Container<EBOOL>{
Container():b(true){}
bool b;
};



<fancy macro goes here that creates me all kind of combinations including for example>
template<>
struct Container<EFLOAT | EBOOL>: public Container<EFLOAT>, public Container<EBOOL>{
Container():Container<EFLOAT>(),Container<EBOOL>(){}
};
</fancy macro>

这样我就可以像这样定义一个变量:

Container<EINT|EFLOAT|EBOOL> myVar;

我该如何定义这个花哨的宏?

我为什么要这个?让它成为乐趣和学习元编程吧

最佳答案

嗯,首先,||是 bool 值或运算符;当你使用它时,它总是会导致 1 (或 true ,而是 true 总是提升为 1 当转换为 int 时,在这种情况下)这在您的代码的情况下等于 EINT ,因此您的模板将始终实例化为 Container<EINT> .

据推测,您正在寻找按位或运算符 | .即便如此,编译器仍将实际按位或值,因此您将获得 7 的值。这将导致使用非专用模板,这将失败。

您到底想什么?有多种方法可以创建足够灵活的类型来保存多种类型的多个数据,但 or 运算符不会像您在模板参数的上下文中那样远程执行任何操作。

关于C++元编程疯狂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4005260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com