问题
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