gpt4 book ai didi

c++ - 如何制作constexpr交换函数?

转载 作者:行者123 更新时间:2023-12-01 14:59:10 25 4
gpt4 key购买 nike

我正在出于学习目的创建自己的String View类,并且正在尝试使其成为100%constexpr。

为了测试它,我有一个成员函数返回一个哈希值。然后,我在switch语句中构造我的字符串 View ,并调用相同的成员函数(如果通过),则该成员函数已达到其目的。

要学习,我正在使用/读取/比较我的实现与Visual Studio 2017最新更新std::string_view,但是,我注意到,尽管swap被标记为constexpr,但它无论在Visual Studio中还是在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;

这是if的Visual Studio实现:
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]

如果swap在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++ - 如何制作constexpr交换函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46372739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com