odd difference between parentheses and curly brackets

Asked 1 years ago, Updated 1 years ago, 267 views

Regarding the example of cppreference, I don't understand this error.Both should be initialized with two constructors of arguments, but I would appreciate it if you could tell me why the first std:: is an error.

Uniform Initialization - cpprefjp C++ Japanese Reference

#include<iostream>
# include <vector>
# include <iterator>

int main()
{
  // Compilation error! considered function declaration syntax but error because parameter name (std::cin) is namespace-qualified
// std::vector<char>vec(std::istream_iterator<char>(std::cin),
//                      std::istream_iterator<char>());

  // vec is the variable of type std::vector<char> initialized with two constructors.
  std::vector<char>vec { std::istream_iterator<char>(std::cin),
                        std::istream_iterator<char>()};
}

c++ c++11

2022-10-22 09:13

1 Answers

The C++ language is compatible with previous versions.If C++11 introduces uniform initialization using curly braces {}, it does not change the behavior of parentheses ().

// Compilation error! considered function declaration syntax but error because parameter name (std::cin) is namespace-qualified
std::vector<char>vec(std::istream_iterator<char>(std::cin),
                      std::istream_iterator<char>());

has nothing to do with C++11 uniform initialization and causes compilation errors in previous versions.Specifically

 int func(int param1, int param2);

In the same format as , the compiler interprets this line as a prototype declaration of a function.Argument names param1 and param2 are optional in the prototype declaration.Now

  • Return value: std::vector<char> Suitable for type name
  • function name:vec→appropriate identifier
  • param1type:std::istream_iterator<char>(std::cin)Incorrect type name
  • param2 type:std::istream_iterator<char>()Incorrect type name

This results in a compilation error.

Braces () have the disadvantage of being interpreted as a prototype declaration for a function, but braces {} uniform initialization does not have this disadvantage because it has different syntax.


2022-10-22 09:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.