如何制作constexpr交换函数

如何制作constexpr交换函数

本文介绍了如何制作constexpr交换函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于学习目的,我正在制作自己的String View类,并且尝试将其设置为100%constexpr。

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

要对其进行测试,我有一个返回哈希值的成员函数。然后,我在switch语句中构造我的字符串视图,并调用相同的成员函数(如果通过),则该成员函数已充分说明其目的。

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.

要学习,使用/阅读/比较我的实现与Visual Studio 2017最新更新 std :: string_view ,但是,尽管 swap 被标记为 constexpr ,在Visual Studio和g ++中均不起作用。

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++.

这是不起作用的代码:

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;

这是Visual Studio的if实现:

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

这是我的课程,与Visual Studio中的相似。

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

所有构造函数和赋值都标记为constexpr。

All constructors and assignments are marked as constexpr.

Visual Studio和g ++都给我类似的错误。

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]

如果swap不适用于constexpr,为什么要使用constexpr?

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

推荐答案

交换被标记为 constexpr constexpr 函数中调用,例如:

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

这篇关于如何制作constexpr交换函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:35