Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can std::reference_wrapper<int> use opretor += if std::reference_wrapper doesn't have operator+=

[Solved] Thank you all, I didn’t even know about user-defined conversion function and how it works.

Why it’s possible to use std::reference_wrapper::operator+=, if such operator does not exist, are there some implicit conversions?

#include <iostream>
#include <functional>
#include <boost/type_index.hpp>

using boost::typeindex::type_id_with_cvr;

template <typename C>
void test(C c)
{
    c += 1;
}

int main()
{
    int a = 3;
    test(a);
    std::cout << a << std::endl;
    test(std::ref(a));
    std::cout << a << std::endl;dd
}

Output: 3 4

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To check that template works perfectly fine:

void test_2(std::reference_wrapper<int> c)
{
    c += 1;
}
int main()
{

    int a = 3;
    test_2(std::ref(a));
    std::cout << a << std::endl;
}

Output: 4

Still works as before. How is that possible?

Funny thing, that in auto d = b + c. d has an integer type.

int main()
{
    auto b = std::ref(a);
    auto c = std::ref(a);
    auto d = b + c;
    std::cout << type_id_with_cvr<decltype(d)>).pretty_name() << std::endl;
}

Output: int

>Solution :

It’s because it’s implicitly convertible to a reference to T:

/* constexpr [c++20] */ operator T& () const noexcept;

In your case, it’s implicitly convertible to an int&.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading