c – 像“if constexpr”,但是类的定义

前端之家收集整理的这篇文章主要介绍了c – 像“if constexpr”,但是类的定义前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_301_0@
如果constexpr是在C程序中摆脱预处理器的一大步骤.但是它仅在函数中有效 – 就像在这个例子中一样:
  1. enum class OS
  2. {
  3. Linux,MacOs,MsWindows,Unknown
  4. };
  5.  
  6. #if defined(__APPLE__)
  7. constexpr OS os = OS::MacOs;
  8. #elif defined(__MINGW32__)
  9. constexpr OS os = OS::MsWindows;
  10. #elif defined(__linux__)
  11. constexpr OS os = OS::Linux;
  12. #else
  13. constexpr OS os = OS::Unknown;
  14. #endif
  15.  
  16. void printSystem()
  17. {
  18. if constexpr (os == OS::Linux)
  19. {
  20. std::cout << "Linux";
  21. }
  22. else if constexpr (os == OS::MacOs)
  23. {
  24. std::cout << "MacOS";
  25. }
  26. else if constexpr (os == OS::MsWindows)
  27. {
  28. std::cout << "MS Windows";
  29. }
  30. else
  31. {
  32. std::cout << "Unknown-OS";
  33. }
  34. }

但是摆脱预处理器的梦想并不十分满意 – 因为以下示例不能编译:

1不能在类定义中使用它来定义类的一些成员:

  1. class OsProperties
  2. {
  3. public:
  4. static void printName()
  5. {
  6. std::cout << osName;
  7. }
  8. private:
  9. if constexpr (os == OS::Linux)
  10. {
  11. const char* const osName = "Linux";
  12. }
  13. else if constexpr (os == OS::MacOs)
  14. {
  15. const char* const osName = "MacOS";
  16. }
  17. else if constexpr (os == OS::MsWindows)
  18. {
  19. const char* const osName = "MS Windows";
  20. }
  21. else
  22. {
  23. const char* const osName = "Unknown";
  24. }
  25. };

2它不适用于类范围:

  1. if constexpr (os == OS::Linux)
  2. {
  3. const char* const osName = "Linux";
  4. }
  5. else if constexpr (os == OS::MacOs)
  6. {
  7. const char* const osName = "MacOS";
  8. }
  9. else if constexpr (os == OS::MsWindows)
  10. {
  11. const char* const osName = "MS Windows";
  12. }
  13. else
  14. {
  15. const char* const osName = "Unknown";
  16. }

我几乎肯定这是根据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号,过去几年没有一个进入这个领域.

而且他们永远不可能.

猜你在找的C&C++相关文章