Alex Rivera | Logout

Concat two `const char` string literals

Asked 2012-11-08T15:36:11.667
17

Is it possible to concat two string literals using a constexpr? Or put differently, can one eliminate macros in code like:

#define nl(str) str "\n"

int main()
{
  std::cout <<
      nl("usage: foo")
      nl("print a message")
      ;

  return 0;
}

Update: There is nothing wrong with using "\n", however I would like to know whether one can use constexpr to replace those type of macros.

Edit
Report

1 Answer

1
  • You cannot return a (plain) array from a function.
  • You cannot create a new const char[n] inside a constexpr (§7.1.5/3 dcl.constexpr).
  • An address constant expression must refer to an object of static storage duration (§5.19/3 expr.const) - this disallows some tricks with objects of types having a constexpr ctor assembling the array for concatenation and your constexpr fct just converting it to a ptr.
  • The arguments passed to a constexpr are not considered to be compile-time constants so you can use the fct at runtime, too - this disallows some tricks with template metaprogramming.
  • You cannot get the single char's of a string literal passed to a function as template arguments - this disallows some other template metaprogramming tricks.

So (as far as I know), you cannot get a constexpr that is returning a char const* of a newly constructed string or a char const[n]. Note most of these restrictions don't hold for an std::array as pointed out by Xeo.

And even if you could return some char const*, a return value is not a literal, and only adjacent string literals are concatenated. This happens in translation phase 6 (§2.2), which I would still call a preprocessing phase. Constexpr are evaluated later (ref?). (f(x) f(y) where f is a function is a syntax error afaik)

But you can return from your constexpr fct an object of some other type (with a constexpr ctor or that is an aggregate) that contains both strings and can be inserted/printed into an basic_ostream.


Edit: here's the example. It's quite a bit long o.O Note you can streamline this in order just to get an additional "\n" add the end of a string. (This is more a generic approach I just wrote down from memory.)

Edit2: Actually, you cannot really streamline it. Creating the arr data member

answered 2012-11-08T16:26:08.153

Your Answer