条件定义变量(静态 if)
在多种情况下,我想使用类似
template<bool condition>
struct S
{
int value;
if constexpr(condition) /*#if condition*/
double my_extra_member_variable;
/*#endif*/
}
或的
if constexpr(sizeof...(Ts) != 0)
// define something extra ( a tuple or so )
东西,这可以通过预处理器标志来实现,但我们希望成为不使用预处理器标志的“酷孩子”,而是使用元编程
在某些情况下它也可以与专业化一起使用,但是假设您有多个条件,并且需要有条件地激活多个成员变量,它可能会很快变得令人讨厌。
我尝试过
constexpr in_series_production_mode = false;
struct dummy{ dummy(auto& x){}; operator=(auto& x){return *this;} }; /*1 byte*/
struct debug_data_t { /* lots of parameters with big size*/};
template <typename T>
using maybe_empty = typename std::conditional<in_series_production_mode ,T,dummy>::type;
maybe_empty<debug_data_t> my_debugging_variable;
,但是这样你仍然会得到 1 个字节用于未使用的虚拟变量。而如果您使用类似的 #if
,您将需要 0 个字节。
有人知道更好的做法吗?
In multiple cases I would want to use something like
template<bool condition>
struct S
{
int value;
if constexpr(condition) /*#if condition*/
double my_extra_member_variable;
/*#endif*/
}
or
if constexpr(sizeof...(Ts) != 0)
// define something extra ( a tuple or so )
This is possible with preprocessor flags, but we want to be the "cool kids" that don't use preprocessor flags, but rather metaprogramming
It could also work with specilizations in some cases, but assume you have multiple conditions, and multiple member variables that need to be conditionally activated, it could get nasty quite fast.
I tried
constexpr in_series_production_mode = false;
struct dummy{ dummy(auto& x){}; operator=(auto& x){return *this;} }; /*1 byte*/
struct debug_data_t { /* lots of parameters with big size*/};
template <typename T>
using maybe_empty = typename std::conditional<in_series_production_mode ,T,dummy>::type;
maybe_empty<debug_data_t> my_debugging_variable;
But with that you still get 1 byte for the unused dummy
variable. While if you used #if
of something similar you would have needed 0 bytes.
Does anybody know a better practice for that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 C++20 中,“足够好”的解决方案是使用
[[no_unique_address]]
属性。它并不完美,因为
var
始终被定义,但它不会需要任何空间。请注意,如果有多个变量,您将需要它们是不同的类型,例如In C++20, the "good enough" solution is with the
[[no_unique_address]]
attributeIt's not perfect because
var
is always defined, but it will not take any space. Note that if there are multiple variables, you will need them to be different types, e.g.