c++visual-studiokeyword

I want to force a certain keyword when creating a function


For example, all functions must include the _inline keyword. If not, a build error should occur.

_inline int somefunction()
{
     return 0;
}

int somefunction2()
{
     return 0;
}

int main() 
{
     somefunction();
     somefunction2(); // build error!
}

This is to prevent certain functions from missing certain keywords due to human error.

Is this possible?


Solution

  • Under the assumption that this is an xy-problem and you have no specific reason to inline all the functions because you didn't state one:

    Trust your compiler.

    If the definition of the function is in the same translation unit as the callsite, the compiler will generally be able to inline the function. All common C++ compilers are very good at deciding wether it's actually a good idea to inline a function or not. Unless you have very specific requirements on why you need your function to be inlined, the compiler will probably make a better decision than you could make yourself.

    Note that unconditionally inlining all function calls is rarely a good idea. It will drastically increase binary size which then leads to many instruction cache misses, which will slow down your program.

    If the definition of the function is in another translation unit than the call site, no inline keyword (or __always_inline__ or other compiler extensions) will make the compiler inline the function, because it does not see the definition. That is unless you enable link time optimization, but in that case you can again trust your compiler to make a good decision.