Boost logo

Boost Users :

From: Paul Mensonides (pmenso57_at_[hidden])
Date: 2007-02-24 17:16:33


> -----Original Message-----
> From: boost-users-bounces_at_[hidden]
> [mailto:boost-users-bounces_at_[hidden]] On Behalf Of Eric Lemings

Hi Jeff.

> I was wondering if the following can be done with Boost
> Preprocessor. Given a list of preprocessor macro names,
> write a simple program that prints whether each macro is
> defined and its value if it is defined.
>
> In particular, I'd like to know if the following example
> program could be reduced/simplified with Boost:

Not really. The problem is that you can't have macros expand to a use of the
"defined" operator. You can condense it a bit:

#include <iostream>

inline void out(bool d, const char* n, const char* v) {
    if (d) {
        std::cout << n << " is defined as" << v << '\n';
    }
    else {
        std::cout << n << " is not defined.\n";
    }
    return;
}

#define STRING(x) #x
#define BOTH(x) #x, STRING(: x)

int main() {
    out(
        #if defined __mips
            1
        #endif
        + 0, BOTH(__mips));
    out(
        #if defined __unix
            1
        #endif
        + 0, BOTH(__unix));
    // ...
    return 0;
}

Note that, in current C++, you have to pass something else to the secondary
STRING macro in BOTH in case x expands to nothing--to avoid an empty argument,
which is undefined. (This will be allowed in C++0x when placemarkers ala C99
are adopted.)

If you aren't worried about the (semi-pathological) case where a macro is
defined as itself (e.g.)

    #define MACRO MACRO

...you can eliminate the preprocessor conditional and just do a runtime string
comparison and make the listing really short.

#include <iostream>
#include <string>

inline void out(const std::string& n, const std::string& v) {
    if ((": " + n) != v) {
        std::cout << n << " is defined as" << v << '\n';
    }
    else {
        std::cout << n << " is not defined.\n";
    }
    return;
}

#define STRING(x) #x
#define OUT(x) out(#x, STRING(: x));

int main() {
    OUT(__mips)
    OUT(__unix)
    OUT(__sgi)
    // ...
    return 0;
}

Regards,
Paul Mensonides


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net