加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 02:59:16 所属栏目:百科 来源:网络整理
导读:如果constexpr是在C程序中摆脱预处理器的一大步骤.但是它仅在函数中有效 – 就像在这个例子中一样: enum class OS{ Linux,MacOs,MsWindows,Unknown};#if defined(__APPLE__)constexpr OS os = OS::MacOs;#elif defined(__MINGW32__)constexpr OS os = OS::M
如果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号,过去几年没有一个进入这个领域.

而且他们永远不可能.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读