C++ 告诉一个不以'\0';除了编译时的C样式字符串之外
是否可以在编译时将不以C++ 告诉一个不以'\0';除了编译时的C样式字符串之外,c++,templates,C++,Templates,是否可以在编译时将不以'\0'结尾的常量字符数组与C样式的字符串区分开来 假设我想为一个类编写两个构造函数 一个构造函数从C样式的字符串构造,该字符串以'\0'结尾 另一个构造函数具有不同的行为,它从一个不以'\0'结尾的常量字符数组中构造 作为一个简单的例子,请考虑 #包括 #包括 结构Foo { Foo(常量字符*) { std::coutNo,以这种方式是不可能的。当重载解析时,非模板函数更可取 非模板函数是一等公民 当模板函数和非模板函数都可以解析函数调用时,将选择非模板函数 可能的解
'\0'
结尾的常量字符数组与C样式的字符串区分开来
假设我想为一个类编写两个构造函数
一个构造函数从C样式的字符串构造,该字符串以'\0'
结尾
另一个构造函数具有不同的行为,它从一个不以'\0'
结尾的常量字符数组中构造
作为一个简单的例子,请考虑
#包括
#包括
结构Foo
{
Foo(常量字符*)
{
std::coutNo,以这种方式是不可能的。当重载解析时,非模板函数更可取
非模板函数是一等公民
当模板函数和非模板函数都可以解析函数调用时,将选择非模板函数
可能的解决办法:
struct Foo
{
void Cstr(const char *)
{
std::cout << "a C-style string" << std::endl;
}
template<size_t N>
Foo(const char (&s)[N])
{
if (N > 0 && !s[N - 1])
Cstr(s);
else
std::cout << "a const char array "
"that does not ends with '\\0'" << std::endl;
}
};
structfoo
{
无效Cstr(常量字符*)
{
std::cout一件有趣的事情是,如果在数组声明中删除const
,它将与数组构造函数一起使用
#include <cstddef>
#include <iostream>
struct Foo
{
Foo(const char *)
{
std::cout << "a C-style string" << std::endl;
}
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");
// const char a[3] {'a', 'b', 'c'};
char a[3] {'a', 'b', 'c'};
Foo foo(a);
return 0;
}
#包括
#包括
结构Foo
{
Foo(常量字符*)
{
std::我很感谢你的观察。没错,但这会改变用户代码,因此不是一个真正的解决方案。是的,我只是弹出观察结果,看看是否有人可以解释,这可能会导致一个正确的解决方案