Why does the concat macro line not work for this "+" case?

Short question:

Are special characters allowed, such as +, -for string concatenation macros ##? For instance,

#define OP(var) operator##var

will OP(+)deploy to operator+?

Exact problem:

#include "z3++.h"
#include <unordered_map>

namespace z3 {
z3::expr operator+(z3::expr const &, z3::expr const &);
}

typedef z3::expr (*MyOperatorTy)(z3::expr const &, z3::expr const &);

#define STR(var) #var
#define z3Op(var) static_cast<MyOperatorTy>(&z3::operator##var)
#define StrOpPair(var) \
  { STR(var), z3Op(var) }

void test() {
  std::unordered_map<std::string, MyOperatorTy> strOpMap1{
      {"+", static_cast<MyOperatorTy>(&z3::operator+)}};  // fine
  std::unordered_map<std::string, MyOperatorTy> strOpMap2{StrOpPair(+)}; // error
}

For strOpMap2, using clang++ -c -std=c++11, he reports:

error: pasting formed 'operator+', an invalid preprocessing token

using g++ -c -std=c++11, it gives:

error: pasting "operator" and "+" does not give a valid preprocessing token

After reading the manual from gcc , I think it should be possible concat, but why do both compilers emit errors?

+4
source share
1 answer

You can insert punctuation to form another punctuation, for example.

#define PASTE(a,b) a##b

int main()
{
     int i = 0;
     i PASTE(+,+);
     // i == 1 now
}

## . . :

PASTE(i,++)

i++ ; i ++.

- (N3797):

  • -
  • -
  • ---Punc
  • ,

: ; , , () . , , .

operator+ : operator +. ##; .

#define OP(punc) operator punc
+5

All Articles