简体   繁体   中英

C++: Is there any sense using the “extern” keyword for templates?

Consider the following example:

fnc.h:

#include <iostream>

template <class T> //common template definition
void fnc()
{
    std::cout << "common";
}

fnc.cpp:

#include "fnc.h"

template<> //specialization for "int"
void fnc<int>()
{
    std::cout << "int";
}

main.cpp

#include "fnc.h"

extern template void fnc<int>(); // compiler will not generate fnc<int> and linker will be used to find "fnc<int>" in other object files

int main()
{
    fnc<double>(); //using instantiation from common template
    fnc<int>(); using specialization from "fnc.cpp"
}

Then I replace extern template void fnc<int>(); with template<> void fnc<int>(); and assume the behavior will be same. Is there any real meaning to using the extern keyword with templates or was it introduced for readability only?

It's not for specializations. Technically what you did is ill-formed, no diagnostic required. You have an explicit instantiation declaration , but no matching definition . The explicit specialization doesn't count for matching against the declaration you provided (even though some compilers implement it in a way that hides the fact).

This construct is for deferring instantiation, to make a compiler not try to instantiate the template in the current translation unit. So you may use it for hiding the template completely and exposing only for a finite set of types:

Header:

template <class T>
void fnc();

extern template void fnc<int>(); // The instantiation is elsewhere.

Source:

template <class T> //common template definition
void fnc()
{
    std::cout << "common";
}

template void fnc<int>(); // explicit instantiation

Or to prevent a frequently used specialization from being instantiated in every TU:

Common header:

#include <vector>
extern template std::vector<unsigned char>; // look for member definitions elsewhere.

One source file:

template std::vector<unsigned char>; // The member functions are defined in this TU

The later use case may save a on compile times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM