我如何制作constexpr交换函数

How do I make a constexpr swap function?

本文关键字:交换 函数 constexpr 何制作      更新时间:2023-10-16

我正在为学习目的做自己的字符串视图类,我正在尝试使其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