Question

What has the meaning the "using of template keyword in the function declaration"?

In this example compiler errors with error: "func" is not a template function.

template<typename T>
struct Window {
  T value;
};

template void func(Window<int>, int);

template<typename T>
void func(Window<T>, T) {
}

int main(void) {
}

But below example is ok.

template<typename T>
struct Window {
  T value;
};

template<typename T>
void func(Window<T>, T) {
}

template void func(Window<int>, int);

int main(void) {
}

What is the meaning with "template" in the above case? Is it just indicator that this function is template function?

Was it helpful?

Solution

A declaration that begins with the keyword template and does not have the <pointy braces> immediately afterward is called an explicit instantiation. It means to look up the template definition and plug in the specified template parameters to get a specific function specialization or class specialization. So in the first example, the compiler is complaining it can't instantiate func(Window<int>, int) because it doesn't yet know anything about a template called func.

Explicit instantiations are usually not necessary, since templates can be implicitly instantiated just by attempting to use them. But explicit instantiation gives some control over where and how related linker symbols appear, and can in some cases be used to move a template definition out of a header file into a source file.

OTHER TIPS

This is just because in your first example you have the definition of the template

template<typename T>
 void func(Window<T>, T) {
}

after the forced instantiation that's represented by this line:

template void func(Window<int>, int);

Whereas in the second example they're the right way around.

But the comment to your question is fair, you are asking a basic question ('what does template mean'), which is best answered by a thoroughgoing study of the subject.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top