我如何制作constexpr交换函数
How do I make a constexpr swap function?
我正在为学习目的做自己的字符串视图类,我正在尝试使其100%constexpr。
要测试它,我有一个返回哈希值的成员函数。然后,我在Switch语句中构造我的字符串视图,并调用相同的成员函数,如果通过该函数,该成员函数已完全填充其目的。
要学习,我正在使用/阅读/比较我的实现与Visual Studio 2017最新更新std::string_view
,但是,我注意到,尽管swap
被标记为constexpr
,但它不起作用,也无效在G 中。
这是不起作用的代码:
constexpr Ali::String::View hello("hello");
constexpr Ali::String::View world("world");
// My implementation fails here!
hello.swap(world);
cout << hello << " " << world << endl;
// Visual Studio implementation fails here!
// std::string_view with char const * is not constexpr because of the length
constexpr std::string_view hello("hello");
constexpr std::string_view world("world");
hello.swap(world);
cout << hello << " " << world << endl;
这是视觉工作室的实现:
constexpr void swap(basic_string_view& _Other) _NOEXCEPT
{ // swap contents
const basic_string_view _Tmp{_Other}; // note: std::swap is not constexpr
_Other = *this;
*this = _Tmp;
}
这是我的班级,类似于Visual Studio的班级。
constexpr void swap(View & input) noexcept {
View const data(input);
input = *this;
*this = data;
}
所有构造函数和作业都标记为constexpr。
Visual Studio和G 都给我类似的错误。
// Visual Studio
error C2662: 'void Ali::String::View::swap(Ali::String::View &) noexcept': cannot convert 'this' pointer from 'const Ali::String::View' to 'Ali::String::View &'
// g++
error: passing 'const Ali::String::View' as 'this' argument discards qualifiers [-fpermissive]
如果交换不适用于constexpr,为什么它具有constexpr?
swap
被标记为允许在constexpr
函数中调用constexpr
,例如:
constexpr int foo()
{
int a = 42;
int b = 51;
swap(a, b); // Here swap should be constexpr, else you have error similar to:
// error: call to non-constexpr function 'void swap(T&, T&) [with T = int]'
return b;
}
demo
相关文章:
- 交换函数不是在 C++ 中交换 2D 数组的元素
- 选择排序时交换函数调用的数量和完成的交换次数是否相同?
- 在C++中使用 4 个交换函数修复程序
- 如何使用Struct打印交换函数
- 错误:使用复制和交换习惯用法的交换函数中"operator="的重载不明确
- 从递归向后选择排序函数调用 max 和交换函数
- 使用通用交换函数来缩短代码
- 快速排序中的交换函数给出错误的输出
- 为什么每个STL容器都具有将其定义为成员函数的交换函数
- 使用交换函数交换元素是可以的吗?
- 传递参数、参数、交换函数和随机数生成器
- 如何在这个交换函数(一个单独的链表)中找到错误
- 左值和右值引用的交换函数
- 使用指针的交换函数
- 排序算法的交换函数不适用于排序函数中的参数。
- 为什么使用std::swap不会在外部范围中隐藏其他交换函数
- 交换对象不实现移动语义时的交换函数
- 我如何制作constexpr交换函数
- 在c++中编写交换函数以重新分配结构数组中的成员值
- std::排序和自定义交换函数