Home > Mobile >  Error while using auto as the function return type
Error while using auto as the function return type

Time:03-30

I am learning C using the resources listed here. In particular, i read that we can use the auto type specifier as the return type of a function. So to get clarity over the concept, i tried the following example:

header.h

#pragma once
struct S 
{
    auto f();
};

source.cpp

#include "header.h"

auto S::f() 
{
    return 4;
}

main.cpp


#include <iostream>
#include "header.h"
int main()
{
    S s;
    s.f();
    return 0;
}

But this gives me error saying:

main.cpp:7:9: error: use of ‘auto S::f()’ before deduction of ‘auto’
    7 |     s.f();
      |         ^

My question is why am i getting this error and how to solve this.

CodePudding user response:

The problem is that the function definition must be visible at any point where the function(with auto return type as in your case) is used. Since you've defined(implemented) that member function inside a source file(.cpp), it is not visible when the call expression s.f() is encountered.

To solve this you can put the implementation of the member function inside the header and make use of inline keyword as shown below:

header.h

#pragma once
struct S 
{
    auto f();
};

inline auto S::f() //note the use of inline to avoid multiple definition error
{
    return 4;
}

Note that we've used inline because we've implemented the member function in a header file which will be included in many other source files. That is, to avoid multiple definition error.

CodePudding user response:

When the compiler hits this part of the code:

S s;
s.f();

All it has seen is the contents of the header header.h. If we look in there we can see that the compiler will only get to look at:

struct S 
{
    auto f();
};

How is it supposed to know the return type of f from just this? Answer is, it cannot. So you need to make the definition of f available where it is used. That means you need to put it in the header file:

struct S 
{
    auto f() {
        return 4;
    }
};
/// or
inline auto S::f() { return 4; }

Or better yet, don't abuse auto here. auto can be useful when the type must be deduced because it depends on a template parameter or similar. In your case, the type is very well defined, so it is easier for the user, if you just use it:

struct S {
    int f();  
}
  • Related