elo
elo

Reputation: 531

auto specifier in header file

I have a file Foo.h:

// Foo.h
#pragma once

int foo();

Also I have a Foo.cpp file which implements Foo.h:

//Foo.cpp
#include "Foo.h"

int foo() {
    return 5;
}

Is there a way to make foo function return type auto? It may be useful if I create a function which return value depends on 3rd party library functions, which return value types may change in later versions.

Upvotes: 1

Views: 2138

Answers (2)

TonyK
TonyK

Reputation: 17114

If you want to do that, you need to put the definition of the function (not just the declaration) into the header file. Otherwise, how can the compiler tell the type of foo if it is called from another source file?

And if you want to define a function in a header file, you need to declare it inline, otherwise the linker will complain of multiple definitions.

Upvotes: 4

eerorika
eerorika

Reputation: 238361

Is there a way to make foo function return type auto?

Only by defining the function inline. Which contradicts with your premise that the function is defined in a separate translation unit.

It may be useful if I create a function which return value depends on 3rd party library functions

You can use a type alias for this purpose:

using return_type = 
    std::invoke_result<library_function, some_arg_t>;
return_type foo();

Upvotes: 3

Related Questions