我正在探索我可以从这个答案中采用 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();
}
}
最佳答案
concat
需要 const char (&)[N]
,在这两种情况下,类型都是 const char*
,所以您可以将您的功能更改为:
template<typename A, typename B>
constexpr auto
test1(const A& a, const B& b)
{
return concat(a, b);
}
关于c++ - constexpr c 字符串连接,在 constexpr 上下文中使用的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39199564/