-->

How do I make a constexpr swap function?

2019-08-22 05:06发布

问题:

I'm making my own String View class for learning purposes, and I'm trying to make it 100% constexpr.

To test it, I have a member function that returns an hash value. I then construct my string view in a switch statement and call that same member function, if it passes, that member function has fullfiled its purpose.

To learn, I'm using / reading / comparing my implementation with Visual Studio 2017 latest update std::string_view, however, I've noticed that, despite swap being marked as constexpr, it does not work, nor in Visual Studio, nor in g++.

This is the piece of code that does not work:

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;

And this is Visual Studio implementation of if:

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;
        }

This one is from my class and it's similar to the one from Visual Studio.

constexpr void swap(View & input) noexcept {
    View const data(input);
    input = *this;
    *this = data;
}

All constructors and assignments are marked as constexpr.

Both Visual Studio and g++ give me similar errors.

// 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]

If swap doesn't work with constexpr, why have it constexpr?

回答1:

swap is marked constexpr to be allowed to be called in constexpr functions, for example:

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