简体   繁体   中英

C Preprocessing Token concatenation

How do I use C preprocess to automatically generate the following code pattern (accessor)?

// Immutable accessor.
const auto& member1 () const {
  return _member1;  // private class member
}

// Mutable accessor.
auto& member1() {  
  return _member1;  // private class member
}

I tried the following but it didn't work...

#define EXPAND_ACCESSOR(item) constexpr const auto& ##item() const { return _##item; } \
                              constexpr auto& ##item() { return _##item; }


EXPAND_ACCESSOR(member1)  // didn't work

You can use a macro to accomplish what you are trying. Your macro needs a few tweaks. (I am using three lines to help with the answer)

You have:

#define EXPAND_ACCESSOR(item) \
   constexpr const auto& ##item() const { return _##item; } \
   constexpr auto& ##item() { return _##item; }

Problems with the macro:

   constexpr const auto& ##item() const { return _##item; } \
                         ^^ Not appropriate.

I get the following error from g++:

error: pasting "&" and "member1" does not give a valid preprocessing token

You need to use just:

#define EXPAND_ACCESSOR(item) \
   constexpr const auto& item() const { return _##item; } \
   constexpr auto& item() { return _##item; }

That fixes the proprocessor errors but it leads to errors related to return type. When you have auto in the return type, you'll need to using a trailing return type.

Use of constexpr with the non- const member function is not appropriate. When a member function is qualified with constexpr , it is assumed to be const member function. Hence, you need to remove the constexpr from that function.

Here's a fixed up macro that should work:

#define EXPAND_ACCESSOR(item) \
   constexpr const decltype( _ ## item) & item() const { return _ ## item; } \
   decltype( _ ## item) & item() { return _ ## item; }

typedef syntax:

typedef struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
 } Book;

'Book' is replaced with the whole struct definition before. ; are valid within {}.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM