Aru*_*run 4 c++ class c++17 if-constexpr
是否可以执行以下操作:
template <unsigned majorVer, unsigned minorVer>
class Object
{
public:
if constexpr ((majorVer == 1) && (minorVer > 10))
bool newField;
else
int newInt
};
Run Code Online (Sandbox Code Playgroud)
或者
template <unsigned majorVer, unsigned minorVer>
class Object
{
public:
if constexpr ((majorVer == 1) && (minorVer > 10))
bool newField;
// Nothing other wise
};
Run Code Online (Sandbox Code Playgroud)
使用 C++17?我想根据一些可以在编译时检查的条件来更改类的结构。有没有办法实现这一目标?
你不能用if constexpr这个。您必须使用以下内容将它们折叠为一个成员std::conditional:
std::conditional_t<(majorVer == 1) && (minorVer > 10), bool, int> newField;
Run Code Online (Sandbox Code Playgroud)
或者,您可以将这两种字段中的每一种都包装在它们自己的类型中:
struct A { bool newField; };
struct B { int newInt; };
Run Code Online (Sandbox Code Playgroud)
并且要么继承std::conditional_t<???, A, B>要么拥有其中之一作为成员。
对于您想要一个成员或什么都不想要的情况,另一种情况只需要是一个空类型。在 C++20 中,这是:
struct E { };
[[no_unique_address]] std::conditional_t<some_condition(), bool, E> newField;
Run Code Online (Sandbox Code Playgroud)
在 C++17 及更早版本中,您需要从这里继承以确保空基优化开始:
struct B { bool field; };
struct E { };
template <unsigned majorVer, unsigned minorVer>
class Object : private std::conditional_t<some_condition(), B, E>
{ ... };
Run Code Online (Sandbox Code Playgroud)