But recently I read some articles about c++ and not once I see people say
S x(); // declaration of function
So I am confusing...Is this means
std::vector<int> list(); // instantiate vector
is a wrong syntax or not proper syntax that we should avoid to do this?
====Update====
Thanks for the reply.
The goal of this question is to seek an explanation why my compiler still can recognize a function declaration as vector instantiation? Is the compiler really such intelligent or I am just lucky?
there is another version where template <> brackets double up forming a >> or << operation that can blow out a compiler. I think the standard suggested fix there was add a space between.
The goal of this question is to seek an explanation why my compiler still can recognize a function declaration as vector instantiation? Is the compiler really such intelligent or I am just lucky?
It doesn't. Or you're unlucky and have a buggy compiler. Or there's a confusing game of "telephone"/"chinese whispers" going on. Show a minimum reproducible example and tell us the exact compiler + version.
@waschbaerYOYO,
If you update your original question after everyone has replied to the original form then this thread will become a shambles.
The form with rounded brackets () is a function declaration, not an instantiation of a vector. It might look like it if that statement is outside any other function and the function has actually been defined - because that function obviously has to return a vector. But it's not a vector instantiation. You don't need ANY brackets for that, and the empty {} form is pointless in this instance because it does nothing different to having no brackets at all.
Please show us the complete, compileable specific code you are referring to. If you try to use a vector's member function, say
list.clear();
then the compiler will complain, because list is not a vector object here.
> why my compiler still can recognize a function declaration as vector instantiation?
Does it? What is the compiler and version?
Current versions of the GNU, LLVM and Microsoft compilers disambiguate it as a function declaration; and with warnings enabled, a warning is issued.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <vector>
int main()
{
std::vector<int> list();
// g++: warning: empty parentheses were disambiguated as a function declaration
// 6 | std::vector<int> list();
// | ^~
// clang++: warning: empty parentheses interpreted as a function declaration
// note: replace parentheses with an initializer to declare a variable
// std::vector<int> list();
// ^~
// {}
// vc++: warning: 'std::vector<int,std::allocator<int>> list(void)': prototyped function not called (was a variable definition intended?)
}
#include <vector>
int main()
{
std::vector<int> list(); // Without warnings set your compiler might get past this
list.clear(); // But it should completely fail here
}