具有两个参数的向量构造函数作为函数声明被解析 [英] Vector constructor with two parameters is parsed as a function declaration

查看:123
本文介绍了具有两个参数的向量构造函数作为函数声明被解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个例子:

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

int main()
{
    std::string sen = "abc def ghi jkl";
    std::istringstream iss(sen);

    std::vector<std::string>    // declaration in question
    vec(std::istream_iterator<std::string>(iss),
        std::istream_iterator<std::string>());

    std::copy(vec.begin(), vec.end(),
              std::ostream_iterator<std::string>(std::cout, "\n"));
}

编译器在调用 std时抛出错误:: copy

请求'vec'中的成员'begin',它是非类型的。 ..

我可以绕过这样的错误:

I can get around the error like this:

std::istream_iterator<std::string> it_begin(iss);
std::istream_iterator<std::string> it_end;
std::vector<std::string> vec(it_begin, it_end);

或通过在每个参数周围加上括号,如下所示:

or by putting parentheses around each parameter, like this:

std::vector<std::string>
vec((std::istream_iterator<std::string>(iss)),
    (std::istream_iterator<std::string>()));

或者甚至在C ++ 11中新的统一初始化:

or even with the new uniform initialization in C++11:

std::vector<std::string> vec { /*begin*/, /*end*/ };

为什么编译器将示例中的声明解析为函数声明?我知道最烦琐的解析,但我认为只有发生在空参数列表。

Why is compiler parsing the declaration in the example as a function declaration? I know about most vexing parse, but I thought that only happens with empty parameter lists. I also wonder why the second workaround works.

推荐答案

这仍然是最烦琐的解析。

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说:

<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

真正的关键是,你的参数名称可以( iss (iss)),而不更改声明的语义。有时

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);
}

输出 42

这篇关于具有两个参数的向量构造函数作为函数声明被解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆