Search code examples
c++friend-function

Trailing return type for a friend function that accepts class arguments


For the below code :

using std::string;

class person
{
private:
    string fname, lname;
    double salary;
public:
    person(string, string, double); // ctor declaration
    ~person(); // dtor declaration
    double operator+(person);
    friend auto salary_burden(person x, person y) -> decltype(x+y); // salary burden of two employees
};

I got a red squiggly below y inside decltype for which Intellisense says cannot convert to incomplete class "person"

What is this all about?

Note : The definitions for the methods including ctors and dtors are in a different translation unit. I guess that is not the cause of the error here.


Solution

  • The issue is because even when the operand of decltype might be of incomplete type, the same don't hold to subexpressions used to form the prvalue that act as operand of decltype

    decltype(x+y);
    

    is equivalent to

    decltype(operator+(x, y));
    

    but person is incomplete inside it own definition. You can circumvent this by defining operator+ as:

    double operator+(person const&);