explicit template's instantiation declaration

 Wed, 14-Jun-2023 11:44:07

显式实例化声明

following text is from stackoverflow.com.

example code:

A.h

#pragma once

template<typename T>
class A
{
public:
    A(T t);

private:
    T _t;
};
A.cpp

#include "A.h"

template<typename T>
A<T>::A(T t) : _t(t) {}

template class A<int>; // explicit instantiation
main.cpp

#include "A.h"

int main()
{
    A<int> a(5); // fine, compiler generates header file,
                 // linker links with implementation from A.cpp file

    // A<float> b(3.14f); // linker error, as expected
}

When you put an explicit instantiation definition in the file A.cpp, how is the compiler supposed to know it's there when compiling main.cpp? The answer is that it can't, so it would still instantiate the templates used in main.cpp, and in your case using the explicit instantiation definition is useless and doesn't help.

A declaration of an explicit instantiation says to the compiler "do not bother instantiating this template, I will do so myself, somewhere else in the program", and the definition is what fulfils that promise.

The explicit instantiation must be defined exactly once, in only one file, but it can be declared multiple times in different files. This is nothing unique to templates, in C and C++ the same rules apply to (non-inline) functions: you can declare them multiple times in different files (usually by putting the declaration in a header) and then you must define the function exactly once, in one file.

So to make your example work properly you should add a declaration in A.h:

extern template class A<int>; // explicit instantiation declaration