0
votes
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
Next time, please do a search on the "error" to see if the question wasn't asked before, before asking (or at the very least - include it in the question). Note: this is not, technically, an error.Algirdas Preidžius
This is not duplicate, because I have interested about conceptual differences between function and variable declarationsuser3514538
"This is not duplicate, because I have interested about conceptual differences between function and variable declarations" 1) Your question mentions nothing about this. Hence, it is still a duplicate, to a question, as is. 2) The main difference is obvious: one is a function, while other is a variable.Algirdas Preidžius
@user3514538 According to the answer of the linked post, it can be deduced from the function argument type, it seems the function template specialization shouldn't work either, it has no arguments. Even I'm not sure why gcc and clang accept it...songyuanyao

1 Answers

1
votes

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;