Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constexpr c string concatenation, parameters used in a constexpr context

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

like image 804
Short Avatar asked Aug 29 '16 06:08

Short


1 Answers

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

like image 118
Jarod42 Avatar answered Oct 10 '22 10:10

Jarod42