c++boostmacrosbracketsboost-extension

How Curly Brackets work in Boost::extension, how to make such macros on my own?


I look at how we use Boost::Extension BOOST_EXTENSION_TYPE_MAP_FUNCTION macro.

For example like this:

BOOST_EXTENSION_TYPE_MAP_FUNCTION
{
    std::map<std::string, boost::extensions::factory<service> > &factories(types.get());
    factories["file_service"].set<file_service>();
}

BOOST_EXTENSION_TYPE_MAP_FUNCTION macro is defined in extension.hpp.

I wonder how this macro understands what is in Curly Brackets and how for example expand this macro to something that would cout anything like "Hello extended macro"?


Solution

  • Let me put my comment into an answer...

    A macro is an instruction to the compiler (I use the collective term here) to substitute at that location the symbols defined as that macro, for example

    #define FOO 1
    
    int val = FOO; // at this point, FOO is replaced with 1
    

    (p.s. please don't do this in C++)

    Now, what is happening in your case is that there is a set of symbols (the signature of a function) defined as a macro, so all that happens is the compiler will substitute the macro with the symbols, and the end result would look (roughly) like this:

    void boost_extension_exported_type_map_function(boost::extensions::type_map& types)
    {
        std::map<std::string, boost::extensions::factory<service> > &factories(types.get());
        factories["file_service"].set<file_service>();
    }
    

    Which as you can see is a simple function. You can do this too (but don't unless you have a very good reason)

    #define BOB void foo(std::string const& bar)
    
    BOB
    {
      std::cout << "HEllo: " << bar << std::endl;
    }
    

    It simply allows a user to define their own implementation for that function... presumably somewhere else - it takes the address of that function and uses it via a pointer...