101010 101010 - 1 month ago 9
C++ Question

C preprocessor insert/append token in string literal

I have the following macro:

#define ASSERT_ITERATOR_VALUE_TYPE(Iterator__, Value_type__) \
static_assert(std::is_same<Value_type__, typename Iterator__::value_type>::value, \
"Expected iterator with value type #Value_type__")


In the macro above I'm trying to insert/append the
Value_type__
token in the string literal that's feed in as the second input argument in
static_assert
.

Obviously, this is not what I'm trying to achieve, since if I state the macro as:

ASSERT_ITERATOR_VALUE_TYPE(std::set<int>::iterator, double);


I'll get the message:

error: static assertion failed: Expected iterator with value type #Value_type__
^^^^^^^^^^^^^


where instead I would like to take the message:

error: static assertion failed: Expected iterator with value type double
^^^^^^


Live Demo

Q



Is there some kind of preprocessor sorcery that will help me achieve what I wan't?

Answer
#define ASSERT_ITERATOR_VALUE_TYPE(Iterator__, Value_type__)                      \
static_assert(std::is_same<Value_type__, typename Iterator__::value_type>::value, \
              "Expected iterator with value type " #Value_type__)

You expand the macro parameter into a string literal, and then rely on string literal concatenation.

Comments