constexpr c string concatenation, parameters used in a constexpr context

北慕城南 提交于 2019-12-22 07:21:41

问题


I was exploring how far I could take the constexpr char const* concatenation from this answer: constexpr to concatenate two or more char strings

I have the following user code that shows exactly what I'm trying to do. It seems that the compiler can't see that the function parameters (a and b) are being passed in as constexpr.

Can anyone see a way to make the two I indicate don't work below, actually work? It would be extremely convenient to be able to combine character arrays through functions like this.

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


回答1:


concat need const char (&)[N], and in both of your case, type will be const char*, so you might change your function as:

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

Demo



来源:https://stackoverflow.com/questions/39199564/constexpr-c-string-concatenation-parameters-used-in-a-constexpr-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!