Sum*_*ood 4 c++ c++11 c++14 c++17
我有一个包含s static constexpr
数组的类,const char
我想通过一个c_str()
方法提供它:
class my_class {
private:
static constexpr const char c_str_[6] = {'c', 'h', 'a', 'r', 's', '\0'};
public:
static constexpr const char* c_str() {
return c_str_;
}
};
Run Code Online (Sandbox Code Playgroud)
这有效,但有一个不幸的结果:它从类型中删除指向数组的长度:
decltype(my_class::c_str()) // equivalent to const char*
Run Code Online (Sandbox Code Playgroud)
我真正喜欢的是实现这个目标的一些方法:
decltype(my_class::c_str()) // equivalent to const char[6]
Run Code Online (Sandbox Code Playgroud)
我知道在任何一种情况下返回的对象都是指针; 我只想保留类型中指向数组的长度.样怎么样decltype("string literal")
的const char[15]
,没有const char*
.
有没有办法做到这一点?
你的意思是回复引用c_str_
?
static constexpr decltype(c_str_)& c_str() { return c_str_; }
Run Code Online (Sandbox Code Playgroud)
要么
static constexpr auto& c_str() { return c_str_; }
Run Code Online (Sandbox Code Playgroud)
如果你想要一个指针,只需交换&
为a *
并返回&c_str_
.
如果要显式引用类型,请使用别名:
using T = const char[6];
static constexpr T& c_str() { return c_str_; }
Run Code Online (Sandbox Code Playgroud)
或者,如果你真的讨厌自己:
static constexpr const char (&c_str())[6] { return c_str_; }
Run Code Online (Sandbox Code Playgroud)
请注意,您不能让函数按值返回原始数组.
一个现代的替代方案是返回a string_view
,它基本上是指向字符串和长度的指针的组合.这允许您的函数的用户直接访问长度信息.并且字符串可以以null终止或以非null终止的方式存储my_class
.
据我所知,也string_view
支持constexpr构造函数.
但是这不允许签名const char* c_str()
.如果您受此约束,则字符串必须以空值终止,以允许调用者检索长度(通过计数).
归档时间: |
|
查看次数: |
307 次 |
最近记录: |