gpt4 book ai didi

c++ - 类似于 "if constexpr"但用于类定义

转载 作者:可可西里 更新时间:2023-11-01 15:06:20 30 4
gpt4 key购买 nike

if constexpr 是在 C++ 程序中摆脱预处理器的一大步。然而,它仅适用于函数 - 如本例所示:

enum class OS
{
Linux,
MacOs,
MsWindows,
Unknown
};

#if defined(__APPLE__)
constexpr OS os = OS::MacOs;
#elif defined(__MINGW32__)
constexpr OS os = OS::MsWindows;
#elif defined(__linux__)
constexpr OS os = OS::Linux;
#else
constexpr OS os = OS::Unknown;
#endif

void printSystem()
{
if constexpr (os == OS::Linux)
{
std::cout << "Linux";
}
else if constexpr (os == OS::MacOs)
{
std::cout << "MacOS";
}
else if constexpr (os == OS::MsWindows)
{
std::cout << "MS Windows";
}
else
{
std::cout << "Unknown-OS";
}
}

但是摆脱预处理器的梦想并不十分令人满意——因为以下示例无法编译:

1 不能在类定义中使用它来以不同方式定义类的某些成员:

class OsProperties
{
public:
static void printName()
{
std::cout << osName;
}
private:
if constexpr (os == OS::Linux)
{
const char* const osName = "Linux";
}
else if constexpr (os == OS::MacOs)
{
const char* const osName = "MacOS";
}
else if constexpr (os == OS::MsWindows)
{
const char* const osName = "MS Windows";
}
else
{
const char* const osName = "Unknown";
}
};

2 它也适用于非类范围(如全局范围):

if constexpr (os == OS::Linux)
{
const char* const osName = "Linux";
}
else if constexpr (os == OS::MacOs)
{
const char* const osName = "MacOS";
}
else if constexpr (os == OS::MsWindows)
{
const char* const osName = "MS Windows";
}
else
{
const char* const osName = "Unknown";
}

我(几乎)确定这是根据 C++17 规范,if constexpr 仅在函数体内工作 - 但我的问题是:

Q1 如何在函数中实现类似 if-constexpr 的效果 - 对于 C++1z/C++14 中的类和全局作用域?我不是在这里要求对模板特化的另一种解释......而是与 if constexpr...

具有相似简单性的东西

Q2是否有任何计划为上述范围扩展 C++?

最佳答案

How to achieve the similar effect like if-constexpr in functions - for class and global scope in C++1z/C++14? And I am not asking here for yet another explanation of template specialization...

你基本上只是说,“我想要模板特化,但没有那些讨厌的模板特化。”

if constexpr 是根据编译时结构改变函数行为的工具。模板特化是 C++ 提供的工具,用于根据编译时构造更改定义。它是 C++ 为该功能提供的唯一工具。

现在对于初始化变量的简单情况,您始终可以创建和调用 lambda。 C++17 为 lambda 提供了 constexpr 支持,lambda 可以使用 if constexpr 来决定返回什么值。

Are there any plan to extend C++ for the above mentioned scopes?

没有。 Here are all of the proposals ,而且过去几年没有人深入研究这个领域。

而且他们永远不会这样做的可能性很小。

关于c++ - 类似于 "if constexpr"但用于类定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41118861/

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