c++c++20

How to use a constructed object as a parameter in C++20?


I just switched my version of C++ to C++20 in visual studio and got a gazillion errors.

A lot of them are like this:

class Foo {
  int value;
public:
  Foo(int v) : value(v) {}
};

// A function that does something with a Foo
void bar(Foo& f)
{
  // ...whatever
}

// This gives an error in C++20 but not in C++17
// The message is something like "cannot convert from Foo to T&"
bar(Foo(3));

What's the reason? Is there a trick to fixing this code? There's hundreds of them.


Addition: The code above is a bit useless because I was only thinking about the syntax when I typed it.

The real life cases in my code are things like wrapper classes:

eg.

class DataSource;   // Abstract source of data

// Can read ASCII/UTF8/Unicode from a DataSource
class TextReader {
  DataSource& source;
public:
  TextReader(DataSource& s) : source(s) {}
};   

// Read some text
void readText(TextReader& r)
{
}

void main()
{
   FileDataSource d("file.text");
   readText(TextSource(d));    // Neat!
}

The ability to pass references to temporaries can be a good thing so I don't see why they would remove it and break a lot of code in the process.


Solution

  • There is no reason to keep it as behaviour never was conformant or corect. You need either one these or both:

    void readText(const TextReader& r);
    void readText(TextReader&& r);
    

    Or a template which works as both:

    template<class T> void readText( T&& r )   // enter your peferred way of constraint