Skip to content

[BUG] Error returning ostream expression from a type's streaming operator operator<< #1072

@bluetarpmedia

Description

@bluetarpmedia

Describe the bug
Cppfront reports this error:
a 'forward' return type cannot return a temporary variable
when returning an expression containing a call to ostream::operator<< from a type's streaming operator.

To Reproduce
Run cppfront on this code:

P: @struct type = {
    first: int = 0;
    second: char = '\0';
    operator<<: (inout os: std::ostream, p: P) -> forward std::ostream = {
        return os << '{' << p.first << ",'" << p.second << "'}";
    }
}

cppfront reports this error:
a 'forward' return type cannot return a temporary variable

[Aside: Is forward std::ostream the correct way to generate the desired std::ostream& return type?]

Changing the operator<< implementation to the following succeeds:

operator<<: (inout os: std::ostream, p: P) -> forward std::ostream = {
    os << '{' << p.first << ",'" << p.second << "'}";
    return os;
}

Repro on Godbolt

Additional context
I'm translating the ranges::for_each_n example code from cppreference:

struct P
{
    int first;
    char second;
    friend std::ostream& operator<<(std::ostream& os, const P& p)
    {
        return os << '{' << p.first << ",'" << p.second << "'}";
    }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions