Vector constructor with two parameters is parsed as a function declaration

后端 未结 1 1514
梦毁少年i
梦毁少年i 2020-12-19 11:33

Consider this example:

#include 
#include 
#include 
#include 

int main()
{
    std::string sen          


        
相关标签:
1条回答
  • 2020-12-19 12:02

    It's still the most vexing parse.

    std::vector<std::string>                     // return type
    vec(                                         // function name
        std::istream_iterator<std::string>(iss), // param 1: an iterator called (iss), or just iss
        std::istream_iterator<std::string>()     // param 2: unnamed function 
    );                                           //          returning iterator
    

    geordi says:

    <tomalak> << ETYPE_DESC(vec); std::vector<std::string> vec(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>());
    <geordi> lvalue function taking a istream_iterator<string, char, char_traits<char>, long> , a pointer to a nullary function returning a istream_iterator<string, char, char_traits<char>, long> , and returning a vector of strings
    

    The crux of it, really, is that your parameter names can have parentheses around them (i.e. iss(iss)) without altering the semantics of the declaration. Sometimes.

    Use another set of parentheses that also surround the type, as you showed, to force that first parameter (and, consequently, the second) to be parsed as an expression rather than a declaration.


    If it helps, also consider:

    void foo(int (x)) {
       cout << x;
    }
    
    int main() {
       foo(42);
    }
    

    Output is 42.

    0 讨论(0)
提交回复
热议问题