Tingur
Tingur

Reputation: 162

Namespace-like functionality for macros

In my program, there are a lot of function-like macros, some of them having the same name and parameters. I want to separate them with some rules, kind of like namespaces, but I know we can't group macros with namespaces.

Is there another way to do this?

Note: the macros are not just simple assignments, so many can't be replaced with const variables.

For example, if have two macros:

#define A(B, C, D)  \
{                   \
    D = B * C;      \
}

#define A(B, C, D)  \
{                   \
    D = B / C;      \
}

I want to split them with some namespaces:

/* Pseudocode */
namespace Multiply {
    #define A(B, C, D)  \
    {                   \
        D = B * C;      \
    }
}

namespace Divide {
    #define A(B, C, D)  \
    {                   \
        D = B / C;      \
    }
}

Then be able to call Multiply::A and Divide::A in my program.

Upvotes: 2

Views: 1379

Answers (2)

eerorika
eerorika

Reputation: 238361

EDIT You appear to be asking about function like macros.

Well, there is a thing in C++ that is much like a "function like macro", but obeys namespaces. It's a function. Instead of macro

#define A(B, C, D)  \
{                   \
    D = B * C;      \
}

You could write a function:

int operation(int left, int right) 
{
    return left * right;
}

If you need it to work with other types than int, you can write a function template.

Although, for something as simple as this example, the best option would be to simply write the multiplication as is, without using macro, nor a function.


You could divide your functions as static member functions of different classes. But I would not recommend that. Instead, I recommend you to give up the silly requirement that functions were not allowed to be defined in a namespace.

Upvotes: 3

mdr
mdr

Reputation: 197

Use inline functions. At least for the examples you provided, this is the appropriate thing to do.

If you know the types, you do not need templates. But if you want it to work for any type, you do:

namespace Multiply {
    template<typename BT, typename CT, typename DT>
    void A(BT B, CT C, DT & D)
    {
        D = B * C;
    }
}

Since the template definition is needed anyway, the compiler may always inline.

constexpr may be useful if you intend compile-time execution only. In C++11 it would not work for the above example, I think. But in C++14 it might.

Upvotes: 2

Related Questions