Search code examples
c++boost-mplboost-preprocessorpreprocessor-meta-program

C++ generic programming subtleties


The problem I have is illustrated in the following code.

#include <iostream>

#define X 4

int main()
{

    std::cout << "should be 4: " << X << std::endl;
#define Y X + 4
    std::cout << "should be 8: " << Y << std::endl;

#undef Y
#define Y X+0
#undef X
#define X Y+1

    std::cout << "expecting 5: " << X << std::endl;
}

The error:

test2.cc: In function ‘int main()’:
test2.cc:17: error: ‘X’ was not declared in this scope

The pattern I am trying to emulate is extending a program at code/build level(much like how nginx modules are wired up at compile-time). I need to build up an extensible compile time structure, which is extensible(plugable) by adding #includes to my build, that results in a boost-mpl-vector with a unique name that contains all of my plugins. So if X is the unique end name, X_0, X_1, X_2 are the names that are built up along the way as the vector has mpl-vector push_back applied to it.

I KNOW the abstractions of boost::preprocessor are key, but I don't want to commit the time to researching it just yet, as I'm prototyping part of the system that will eventually be compile-time modularized.

So, for future reference,

  1. Why am I getting an error above ?
  2. What should the correct raw preprocessor pattern look like.
  3. What does the correct boost-preprocessor-library pattern look like.

Solution

  • compiling with g++ -E gives this:

    int main()
    {
    
        std::cout << "should be 4: " << 4 << std::endl;
    
        std::cout << "should be 8: " << 4 + 4 << std::endl;
    
    
    
    
    
    
        std::cout << "expecting 5: " << X+0 +1 << std::endl;
    }
    

    So you can see why you get the error.