如果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规范,如果constexpr只在函数体内工作,但我的问题是:
Q1如何在函数中实现类似于if-constexpr的类似效果 – 对于C 1z / C 14中的类和全局范围?而且我不是在这里询问模板专业化的另一个解释…但是有一些类似简单的东西,就像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…
你基本上只是说,“我想要模板专业化,但没有那么讨厌的模板专业化.”
如果constexpr是基于编译时结构使函数行为发生变化的工具.模板专业化是C提供的工具,用于根据编译时结构使定义更改.它是该功能唯一提供的工具.
现在,您可以简单地初始化变量,您可以随时创建并调用一个lambda. C 17为lambdas提供了constexpr支持,如果constexpr决定要返回什么值,那么lambda就可以使用.
Are there any plan to extend C++ for the above mentioned scopes?
Here are all of the proposals号,过去几年没有一个进入这个领域.
而且他们永远不可能.