-1

My question is the inverse of this question.

I want to write a macro that will accept an integer and a string literal as it's arguments, like so:

#define STRING_MAP_ENTRY(value, name) \
  {value, std::to_string(val) + " - " + name}

STRING_MAP_ENTRY(0, "ENTRY_1")

The macro should turn the above call into {0, "0 - ENTRY_1"}

Is there a way to do this? My current attempt is this:

#define STRING_MAP_ENTRY(val, name) \
  { val, std::to_string(val) + "(" + name + ")" }
Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82

2 Answers2

5

Something like this could work:

#define STRING_MAP_ENTRY(value, name) \
  {value, #value " - " #name}

STRING_MAP_ENTRY(0, ENTRY_1)

the # before a token will stringify it. As for combining them, adjacent string literals will be combined into a single string.

Christian Gibbons
  • 4,272
  • 1
  • 16
  • 29
-1

Why do you want to use macro?

It's not good.

Use this:

auto STRING_MAP_ENTRY(int value_,string name_){
    struct{int value;string name;} pair_{value_,to_string(value_)+string(" - ")+name_};
    return pair_;
}

And use this to check if it works:

auto aa= STRING_MAP_ENTRY(0,string("ENTRY_1"));
cout<<aa.value<<','<<aa.name<<endl; // 0,0 - ENTRY_1

Remember:

Always use FUNCTION not MACRO!!

  • Won't this function do the string-concatenations at runtime? If so, then one reason to prefer the macro would be so that the resulting string will be compiled in to the executable, rather than having the computer burn CPU cycles re-creating the string every time the function is called. – Jeremy Friesner Jul 11 '20 at 03:29
  • Using macro make your code fatter, but function not. The resulting string will be compiled in to the executable means that it's a fixed value, so you can't generate it in runtime. So we can know a fact esaily: Function can improve the Reusability of the code, also other executable can call this function, but macro not because compiler will execute it when it is compile the code. – Awaaaaawwwwa Jul 11 '20 at 06:03
  • If the work can be done at compile time, always use a macro (or constexpr), not a function. That's the opposite of this answer. The more work the compiler/preprocessor can do means the less work your program has to do. To be fair though, I use C++ like C-with-methods mainly because I disagree with some language features/standard library features. – Jimmio92 Jan 21 '22 at 06:52