Search code examples
c++c++14autodecltypetype-deduction

use of decltype(auto) <func> before deduction of auto


Following situation:

#include <stdint.h>

class C
{
public:
    C()=default;
    ~C()=default;
    template<uint8_t> struct integconst
    {
    };

    int m1(integconst<8>);
    int m2(integconst<8>);
    decltype(auto) masterMethod(int opMode);
private:
};

int C::m1(integconst<8>) {return 1;}
int C::m2(integconst<8>) {return 2;}

decltype(auto) C::masterMethod(int opMode)
{
    switch(opMode)
    {
    case 1:
            return m1(integconst<sizeof(uintptr_t)>{}); break;
    case 2:
            return m2(integconst<sizeof(uintptr_t)>{}); break;
    default:
            return m1(integconst<sizeof(uintptr_t)>{}); break;
    }
}

int main()
{
    C obj;
    int bla=obj.masterMethod(1);
    return 0;
}

putting the above simplified example will work with no problems. but when I try to seperate the implementation and declaration in separate files (full example here) then I get the error

main.cpp: error: use of 'decltype(auto) C::masterMethod(int)' before deduction of 'auto'. Moving the implementation directly to the class itself solves the problem (or implementing the methods within the same file), but I don't really understand why? Can somebody explain me why the compiler does not know the type of decltype(auto) yet, respecitvley when does the comiler start to resolve the return types of "auto"? How would one separate the implementation and declaration as I would like to do it?


Solution

  • Every source file (.cpp file or .cc file) has to stand on its own. The standard calls these files translation units, because the behaviour of the program is the same as-if all those files are translated into machine language as separate units, and only then the machine code is linked into one program.

    Standing "on its own" means that the source file together with all files included in it have to convey all information to translate the source file. If you put the masterMethod in one source file and main in a different source file, the compiler has no idea which type is returned by masterMethod when compiling main.

    The answer to your question

    How would one seperate implementation and declaration as I would like to do it?

    Is thus: Either you put the source code of the function in the header file, or you give up on using return type deduction. If you put the source code into the header file, you don't need to put it inside the class definition, as long as you declare it inline.