【问题标题】:constexpr c string concatenation, parameters used in a constexpr contextconstexpr c 字符串连接,在 constexpr 上下文中使用的参数
【发布时间】:2017-01-05 02:09:44
【问题描述】:

我正在探索我可以从这个答案中获得 constexpr char const* 连接多远: constexpr to concatenate two or more char strings

我有以下用户代码,可以准确显示我正在尝试做的事情。似乎编译器看不到函数参数(a和b)是作为constexpr传入的。

任何人都可以找到一种方法来使我在下面指出的两个不起作用,实际上起作用吗?能通过这样的函数来组合字符数组会非常方便。

template<typename A, typename B>
constexpr auto
test1(A a, B b)
{
  return concat(a, b);
}

constexpr auto
test2(char const* a, char const* b)
{
  return concat(a, b);
}

int main()
{
  {
    // works
    auto constexpr text = concat("hi", " ", "there!");
    std::cout << text.data();
  }
  {
    // doesn't work
    auto constexpr text = test1("uh", " oh");
    std::cout << text.data();
  }
  {
    // doesn't work
    auto constexpr text = test2("uh", " oh");
    std::cout << text.data();
  }
}

LIVE example

【问题讨论】:

    标签: c++ c++11 compile-time-constant


    【解决方案1】:

    concat 需要const char (&amp;)[N],在这两种情况下,类型都是const char*,因此您可以将函数更改为:

    template<typename A, typename B>
    constexpr auto
    test1(const A& a, const B& b)
    {
      return concat(a, b);
    }
    

    Demo

    【讨论】:

      猜你喜欢
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-03
      • 2019-06-13
      相关资源
      最近更新 更多