简体   繁体   中英

Extern template with variadic arguments doesn't compile

I try to create a extern template with variadic arguments like:

extern template<typename... XS> void log( XS... xs );

But gcc 7.2 doesn't compile it, and show the error:

error: expected unqualified-id before ‘<’ token

I check the gcc status in c++11, and extern templates should work, isn't it?

The extern keyword does something different than you expect - if I understand correctly what you expect, of course.

The extern keyword is applied to explicit instantiations of a template, and it prevents the compiler from generating implicitly the code for that template while processing a certain translation unit. Per Paragraph 14.7.2/2 of the C++11 Standard:

There are two forms of explicit instantiation: an explicit instantiation definition and an explicit instantiation declaration. An explicit instantiation declaration begins with the extern keyword .

Without the extern keyword, the compiler would generate code for (say) log(double, int) in each translation unit that contains calls to log(double, int) , and this code - which would and should be identical for all translation units - would be eventually merged by the linker (the linker would basically discard all duplicates and keep only one).

The extern keyword saves you from this waste of compilation time by telling the compiler: " Trust me, somebody else will instantiate this template somewhere else - you don't need to do it now ". But that promise must be fulfilled .

So for instance, if you have this primary template:

template<typename... Xs> void log(Xs... xs);

And you declare this explicit instantiation:

extern template void log(int, double);

Than you must have a corresponding explicit instantiation in some translation unit:

template void log(int, double)

Otherwise, the compiler will never ever produce code for log<int, double>(int, double) , and the linker will complain about undefined references.

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