问题
template <class C>
C fnc();
template <>
int fnc(){return 0;}
template <class C>
C var;
template <>
int var = 0; // compile error
int main()
{
}
There's a specialization of a fnc
function declared without an explicit type indication (such as int fnc<int>()
), so the type of template argument is deduced from the function return type, but that thing does not work for variable templates (it leads to compiler error). Is this a correct behavior or a bug in all compilers a have tested (clang, gcc)?
回答1:
Template arguments can only be omitted in explicit specialization of function templates. Since you have a template variable, you have to add the <int>
part:
template <>
int var<int> = 0;
来源:https://stackoverflow.com/questions/61384251/template-specialization-of-variable-template-and-type-deduction