C ++连接两个`const char`字符串字面量 [英] C++ concat two `const char` string literals

查看:311
本文介绍了C ++连接两个`const char`字符串字面量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 constexpr 连接两个字符串文字?或改写可以在代码中消除宏:

  #define nl(str)str\\\


int main()
{
std :: cout<
nl(usage:foo)
nl(打印消息)
;

return 0;
}

更新:使用\\\
,但我想知道是否可以使用 constexpr 替换这些类型的宏。 / p>

解决方案


  1. 是的,完全可以创建编译时常量字符串,他们使用constexpr函数甚至运算符。但是,


  2. 编译器不需要对除静态和线程持续时间对象之外的任何对象执行常量初始化。特别地,临时对象(不是变量,并且具有小于自动存储持续时间的东西)不需要被恒定地初始化,并且就我所知,没有编译器对于数组。定义常量初始化的3.6.2 / 2-3,以及关于块级静态持续时间变量的一些更多措辞的6.7.4。这些都不适用于临时,其生命周期定义在12.2 / 3及以下。


所需的编译时连接为:

  static const auto conc =< some clever constexpr thingy> ;; 
std :: cout<<浓缩

但您不能使用它:

  std :: cout< < some clever constexpr thingy> ;; 

更新



但您可以使其适用于:

  std :: cout< * []() - > const {
static constexpr auto s = / * constexpr call * /;
return& s;}()
<< 一些更多的文本;

但是样板标点太难看了, p>




(免责声明:IANALL,虽然有时候我喜欢在互联网上玩一个,所以可能会有一些灰尘的角落)



(尽管有免责声明,但由@DyP推出,我添加了一些语言 - 律师的引用。)


Is it possible to concat two string literals using a constexpr? Or rephrased 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.

解决方案

  1. Yes, it is entirely possible to create compile-time constant strings, and manipulate them with constexpr functions and even operators. However,

  2. The compiler is not required to perform constant initialization of any object other than static- and thread-duration objects. In particular, temporary objects (which are not variables, and have something less than automatic storage duration) are not required to be constant initialized, and as far as I know no compiler does that for arrays. See 3.6.2/2-3, which define constant initialization, and 6.7.4 for some more wording with respect to block-level static duration variables. Neither of these apply to temporaries, whose lifetime is defined in 12.2/3 and following.

So you could achieve the desired compile-time concatenation with:

static const auto conc = <some clever constexpr thingy>;
std::cout << conc;

but you can't make it work with:

std::cout <<  <some clever constexpr thingy>;

Update:

But you can make it work with:

std::cout << *[]()-> const {
             static constexpr auto s = /* constexpr call */;
             return &s;}()
          << " some more text";

But the boilerplate punctuation is way too ugly to make it any more than an interesting little hack.


(Disclaimer: IANALL, although sometimes I like to play one on the internet. So there might be some dusty corners of the standard which contradicts the above.)

(Despite the disclaimer, and pushed by @DyP, I added some more language-lawyerly citations.)

这篇关于C ++连接两个`const char`字符串字面量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆