在多種情況下,我想使用類似的東西
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 個位元組用于未使用的dummy變數。而如果您使用#if類似的東西,您將需要 0 個位元組。
有人知道更好的做法嗎?
uj5u.com熱心網友回復:
在 C 20 中,“足夠好”的解決方案是使用[[no_unique_address]]屬性
struct empty_t {};
template<bool condition>
struct S {
[[no_unique_address]]] std::conditional_t<condition, double, empty_t> var;
};
它并不完美,因為var它總是被定義,但它不會占用任何空間。請注意,如果有多個變數,您將需要它們是不同的型別,例如
template<int>
struct empty_t {};
template<bool condition>
struct S {
[[no_unique_address]]] std::conditional_t<condition, double, empty_t<0>> var;
[[no_unique_address]]] std::conditional_t<condition, double, empty_t<1>> rav;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/440285.html
