Nobun wrote: |
---|
I saw that templates are not "inline". |
You don't have to use the 'inline' keyword for a function to be inline. These two classes are identical:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
struct C1
{
void f()
{ //definition here makes it implicitly inline
std::cout << "C1::f" << std::endl;
}
};
struct C2
{
inline void f() //inline keyword is optional
{
std::cout << "C2::f" << std::endl;
}
};
|
1. I'm not sure what you mean by the 'scope' of "inline", but it is used usually when you want to let the compiler know it has permission to inline a function or to allow for ODR to activate. When the compiler 'inlines' a function, that means that it takes the behavior of the function and substitutes it directly into where the function is called, like a macro - the benefit is that it eliminates the process of calling the function, passing arguments on the stack, etc. - it is just an optimization to make code run faster. it is not always possible, though.
An example of when inline is required is when you define a non-template non-class function in a header and include that header in multiple source files - without inline, the code will not link because the linker will see multiple definitions of the function. With inline keyword, the compiler will memorize the function and ignore it when it sees it again, so the linker only sees the definition once.
2. For template classes and functions, just define them completely in the header. In my example above, you would remove Template.cpp and change the Template.h header to:
1 2 3 4 5 6 7 8 9 10 11
|
#ifndef MyTemplateHeaderIncludeGuard
#define MyTemplateHeaderIncludeGuard
#include <iostream>
template<typename T>
void ShowValue(T t)
{ //complete definition in header
std::cout << "The value given is \"" << t << '"' << std::endl;
}
#endif
|
In this case you actually don't need include guards, but they are good practice anyway.
The same applies to classes; you would provide the definitions to all the functions inside the class in the header. In fact, this is allowed for classes even if they are not templates, because of how the functions are implicitly inline by being defined within the class.