根据预处理器指令允许使用成员变量 [英] Allow use of member variable depending on preprocessor directives

查看:66
本文介绍了根据预处理器指令允许使用成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下类别:

class Foo 
{
public:
    #ifdef CONDITION
    int x = 0;
    #endif

    int y;

    int foo() { 
        #ifdef CONDITION
        return ++x;
        #else
        return 0;
        #endif
    }
}

int x 仅在我定义 CONDITION 时存在-通过 #define CONDITION 或作为预处理程序定义( -D条件

int x only exists when I define CONDITION - either through a #define CONDITION or as a preprocessor definition (-D CONDITION)

这有一个很好的优点,就是我不能使用 x进行编译在未定义 CONDITION 的地方错误输入。

This has the neat advantage that I can't compile it I use x by mistake somewhere when CONDITION isn't defined.

例如:
错误地写了这样的东西:

For example: If, by mistake, I write something like:

Foo f;
f.x = 10;

当我缺少 -D条件

但是,当在多个项目使用的标头中声明类 Foo 时,我们会遇到各种讨厌的问题,其中预处理器的定义不同:
Foo y 的偏移量将有所不同,从而导致对 Foo 的对象的外观。

However, we get all sorts of nasty problems when class Foo is declared in a header that is used by multiple projects, where preprocessor definitions differ:
The offset of y within Foo will be different, resulting in different interpretations of how an object of Foo looks.

问题:

是否存在我可以为使用 Foo 的任何人声明 x 的某种方式,但在出现以下情况时仍会收到某种编译器警告/错误:我尝试使用它而不定义 CONDITION

The question:
Is there some way in which I can declare x for anyone using Foo, but still get some sort of compiler warning/error when I try to use it without defining CONDITION?

推荐答案

您想要的违反了ODR。更干净的方法是将 CONDITION 用作 bool 模板参数。

What you want is ODR violation. A cleaner approach would have been making CONDITION a bool template parameter.

但是,如果您冒此风险,则可以采用缩小形式来承担风险,仅在属性中差额为 x

But if you take this risk, you can take it in reduced form with difference of x only in attribute:

class Foo 
{
    #ifndef CONDITION
    [[deprecated("Don'u use with [[condition]] defined")]]
    #endif
    int x = 0;
    int y;

}

这篇关于根据预处理器指令允许使用成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆