C++11 constexpr 字符串实现
C++11 constexpr string implementation
有没有办法实现字符串在编译时和运行时工作?
AFAIK 对于要构造的类,它需要有一个简单的析构函数。 但是,当我们处理字符串时,这被证明是困难的。 如果字符串不是 constexpr,那么它需要释放内存。 但是,如果它是 constexpr,那么它是静态分配的,不应该被删除,从而允许一个微不足道的析构函数。
但是,不可能说"嘿,编译器! 如果我是魔术师,你不需要毁掉我!还是吗?
它将如下所示:
class string {
private:
char * str;
public:
template<std::size_t l>
constexpr string(const char (&s)[l]) : str(&(s[0])) {}
string(const char * s) { str = strdup(s); }
static if (object_is_constexpr) {
~string() = default;
}
else {
~string() { free(str); }
}
};
我能够得到的最接近的是有两种单独的类型,字符串和constexpr_string,用户定义的文字_string返回constexpr_string,以及用户定义的从constexpr_string到字符串的隐式转换。
不过这不是很好,因为const auto s = "asdf"_string;
有效,但const string s = "asdf"_string;
不起作用。 此外,指向constexpr_string的引用/指针不会转换。 无论哪种方式,继承都会导致不直观的"陷阱",并且不能解决第一个问题。
这似乎是可能的,只要编译器信任程序员不需要破坏 constexpr。
如果我有误解,请告诉我。
这不仅仅是一个破坏的问题。
一个constexpr
操作应该只调用其他constexpr
操作,new
、malloc
等都不constexpr
。请注意,这是一个静态检查的属性,不依赖于运行时参数,因此必须完全不存在对此类函数的调用,而不仅仅是隐藏在(据说(未采用的分支中。
因此,永远不可能获得constexpr
string
.
在某种程度上,可以查看本页中的代码示例。您可以创建 constexpr conststr
对象并对其调用一些操作,但不能将它们用作非类型模板参数。
- 我如何在C++像在 Python 中一样实现 f 字符串?
- 是否有可能实现O(N)时间和O(1)空间解决方案,以实现C++中的字符串循环移位
- "in-situ without memory allocation" 字符串的愚蠢实现意味着什么?
- 为什么sub_match和basic_string比较运算符使用额外的字符串副本实现?
- 如何实现通用比较?(用于数字和字符串)
- 自定义哈希表实现-将字符串映射到整数时出现内存错误
- 实现一个函数,该函数将字符串作为输入并返回一个新字符串,辅音字母不替换为 "!"
- 如何正确实现 std::all_of 函数来验证字符串的一部分?
- 字符串和向量的shrink_to_fit实现不同?
- std::shared_ptr<std::string const> 可以作为引用计数的不可变字符串的有效实现吗?
- 如何使用 c++ 模板实现整数、字符串、浮点数和日期对象的数组
- 是否有很好的C 实现安全字符串
- C++实现代码中的字符串不应存在于输出二进制文件中.如何解决
- 如何实现将前缀与字符串匹配的最快算法
- C++ 将字符串值传递到实现文件时出现问题
- 在最少的操作中实现字符串所有字符的相同频率。(所有字符的范围从'a'到"z")
- WXSTRING:是否有使用类似Python3的占位符实现字符串格式化的C/C 代码
- 如何在标准模板库中实现字符串的深度同步
- 使用后缀数组和 LCP(-LR) 实现字符串模式匹配
- 实现字符串类 c++