c++templates

Is compiler allowed to ignore inline in case of template specialization?


Lets say you have simple template function (not class member for the sake of simplicity) with type specific specialization in the same .h file...

template <class TYPE>
void    some_function(TYPE& val)
{
    // some generic implementation
}

template <>
inline void some_function<int>(int& val)
{
    // some int specific implementation
}

Unless you explicitly direct you compiler to inline the specialization (inline keyword) you will get linking error if .h file is included more than once (at least I do in Visual C++ 2008).
We all know that inline is just a suggestion to the compiler, which it can ignore. In this particular case is compiler allowed to ignore this suggestion and let linker to fail?


Solution

  • You are misunderstanding the meaning of the often-mentioned "ignore inline" possibility.

    No compiler is ever allowed to ignore the inline specifier used in function declaration and the consequences this specifier has with respect to One Definition Rule (ODR).

    When someone says that compiler are allowed to "ignore inline", it only means that compilers are not required to actually inline the calls to the function in question. To "ignore inline" means to generate an ordinary (non-inlined) function call to an inline function.

    In any case, even if the compiler decided to always generate ordinary calls to an inline function (i.e. to always "ignore inline"), it is still required to treat the function as inline for the purposes of ODR. How the compiler is going to do it is the problem of the compiler. You are not supposed to worry about it.

    In your original example you should not not get any linker errors.