【发布时间】:2020-07-14 02:51:05
【问题描述】:
除了 C 风格的字符串之外,是否可以在编译时告诉一个不以 '\0' 结尾的 const char 数组?
假设我想为一个类编写两个构造函数。
一个构造函数从 C 风格的字符串构造,以 '\0' 结尾。
另一个具有不同行为的构造函数从不以 '\0' 结尾的 const char 数组构造。
作为一个最小的例子,考虑
#include <cstddef>
#include <iostream>
struct Foo
{
Foo(const char *)
{
std::cout << "a C-style string" << std::endl;
}
// Question: How to modify Foo so that a const char array that does not
// ends with '\0' will go to a different constructor?
template<size_t N>
Foo(const char (&)[N])
{
std::cout << "a const char array "
"that does not ends with '\\0'" << std::endl;
}
};
int main()
{
Foo("a C-style string"); // print "a C-style string"
const char a[3] {'a', 'b', 'c'};
Foo foo(a); // print "a C-style string" - can it change?
return 0;
}
使用g++ -std=c++17编译。
问题:有什么办法可以做到吗?
也许我可以应用 SFINAE 技术,但我还没有弄清楚如何去做。
注意:目前 StackOverflow 上有几个类似但不相同的问题。我没有找到直接解决我的问题的问题。
【问题讨论】: