4

If one has a variable template with the type deduced from the initializer by means of auto keyword, for example:

template <typename T>
auto * p = (T*)nullptr;

How to make an instantiation of the variable for a particular type (e.g. to export it from a shared library)?

GCC and Clang way is to replace auto with the specific type:

template int * p<int>;

But it is rejected by MSVC with the error:

error C3410: 'p<int>': the type of the explicit instantiation 'int *' does not match the type of the variable template 'auto *'

Demo: https://gcc.godbolt.org/z/66xModTjK

MSVC demands to make the instantiation as:

template auto * p<int>;

which is in turn rejected by GCC and Clang with some weird messages:

error: 'auto' variable template instantiation is not allowed
error: declaration of 'auto* p<int>' has no initializer

Demo: https://gcc.godbolt.org/z/7j3nh7Whx

Which compilers are right here according to the standard?

Fedor
  • 17,146
  • 13
  • 40
  • 131
  • 3
    "variable template", not "template variable" – 463035818_is_not_an_ai Sep 29 '21 at 07:08
  • 1
    You can do explicit instantiation of variable templates!? – StoryTeller - Unslander Monica Sep 29 '21 at 07:18
  • 1
    [temp.explicit]p6: "The declaration in an explicit-instantiation and the declaration produced by the corresponding substitution into the templated function, variable, or class are two declarations of the same entity. [Note 1: These declarations are required to have matching types as specified in 6.6, except as specified in 14." - That's the only pertinent thing the standard has to say about this. – Sebastian Redl Sep 29 '21 at 07:58
  • 1
    Note that compilers don't even agree on mixing `auto` and explicit types in redeclarations of plain variables. `extern int* i; auto* i = (int*)nullptr;` works in Clang, but fails to compile in GCC and MSVC. – Sebastian Redl Sep 29 '21 at 08:00
  • 1
    Bottom line: don't use `auto` in variable templates. – Sebastian Redl Sep 29 '21 at 08:00
  • 2
    https://timsong-cpp.github.io/cppwp/n4868/temp.explicit#example-2 – Language Lawyer Sep 29 '21 at 11:06
  • @SebastianRedl [Does a declaration using "auto" match an extern declaration that uses a concrete type specifier?](https://stackoverflow.com/questions/26386010/does-a-declaration-using-auto-match-an-extern-declaration-that-uses-a-concrete) – Language Lawyer Sep 29 '21 at 11:08

0 Answers0