Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ macro expanding to argument, argument as string

I have many variables that are named the same as elements in an engineering specification document so the string version of the name is also useful.

I find myself using a macro like this a lot:

#define MACRO(a) a, #a

Typical usage is:

void someFunction(int a, const char *name);

someFunction(MACRO(meaningfully_named_variable));

My question is threefold:

  • Is there a better way of doing this?
  • Is a similar macro available in Boost or other libraries?
  • If not, how could I refine and rename this to make it clear and useful?

Edit I should have said that the above is a minimal example. The function might have other parameters and the named entity might be a data member or perhaps even a function itself.

Another extension I'm considering for C++ is a class NamedRef that could receive the contents of the macro.

template <typename T>
struct NamedRef
{
    NamedRef(T *t, const char *name) : t(t), name(name) { }
    T *t;
    const char *name;
};

template <typename T>
NamedRef<T> namedRef(T &t, const char *name)
{
    return NamedRef<T>(&t, name);
}

#define WITH_NAME(a) a, #a

// more sophisticated usage example
void otherFunction(double, NamedRef<int>, bool);

otherFunction(0.0, namedRef(object.WITH_NAME(meaningful_member_name)), false);
like image 233
paperjam Avatar asked Dec 21 '11 23:12

paperjam


People also ask

Can we pass arguments in macro?

A parameter can be either a simple string or a quoted string. It can be passed by using the standard method of putting variables into shared and profile pools (use VPUT in dialogs and VGET in initial macros).

How do you pass a macro in an argument?

To assign a macro that you pass arguments to a button, shape, image, or any object, you first right-click that object and click Assign Macro and then type the name of the macro and the argument, following the pattern described in the above examples, and then click OK. 'show_msg "I clicked a button!"'

Can a macro argument be converted to constant?

There is no way to convert a macro argument into a character constant. If you want to stringify the result of expansion of a macro argument, you have to use two levels of macros. s is stringified when it is used in str, so it is not macro-expanded first.

What does the '#' symbol do in macro expansion?

The number-sign or "stringizing" operator (#) converts macro parameters to string literals without expanding the parameter definition. It's used only with macros that take arguments.


1 Answers

You could take it a step further:

#define SOMEFUNCTION(a) somefunction(a, #a)

However, this is only useful if you call the same function alot. Otherwise, I don't think there is any better way than your example. Of course, you should change the name of the macro to something more meaningful though, like ARGUMENTS or something.

like image 124
Jesse Good Avatar answered Oct 15 '22 04:10

Jesse Good