【问题标题】:VS2015 cannot convert from 'initializer list' to 'std::string' errorVS2015 无法从 'initializer list' 转换为 'std::string' 错误
【发布时间】:2017-04-24 16:24:39
【问题描述】:
// get the drive letter/network volume portion of the path
    std::string drive_path;
    if (drive_type == disk_util::drive_type_network)
    {
        boost::iterator_range<std::string::const_iterator> r = boost::find_nth(path, "/", 3);
        if (!r.empty())
            drive_path = std::string(path.begin(), r.begin());
    }
    else
    {
        size_t i = path.find('/');
        drive_path = path.substr(0, i);
    }


//path is also a std::string type 

问题来了:drive_path = std::string(path.begin(), r.begin());

这在 VS2013 上编译成功,但在 VS 2015 中抛出错误 错误:error C2440: '': cannot convert from 'initializer list' to 'std::string'

根据 std::string 构造函数,我们有一个 Range 构造函数,它采用迭代器 1 和迭代器 2 来填充字符串。

http://www.cplusplus.com/reference/string/string/string/

    //range (7) 
template <class InputIterator>
  string  (InputIterator first, InputIterator last);

在 VS2013 中,它现在显示任何潜在问题的警告并成功编译。

两个迭代器都是同一个字符串,我不知道为什么这在 VS2015 中失败了。任何帮助表示赞赏。

【问题讨论】:

  • 试试std::string(path.cbegin(), r.begin())

标签: c++ string visual-studio-2013 visual-studio-2015 stdstring


【解决方案1】:

string ctor 要求两个迭代器的类型相同 class InputIterator。你的path.begin()std::string::iteratorr.begin()std::string::const_iterator

我会尝试任何一个(同时使两者都为 const)

drive_path = std::string(path.cbegin(), r.begin());

或(使两者都非const)

boost::iterator_range<std::string::iterator> r;

【讨论】:

  • 使两个相同类型的迭代器解决了这个问题,我真的应该这样做。 :) ,非常感谢
【解决方案2】:

迭代器参数的类型应该与您正在使用的字符串构造函数的类型相同。
我怀疑您将“非常量”迭代器 (path.begin()) 作为第一个参数传递,将 const_iterator 作为第二个参数传递。

您可以尝试同时传递两个 const_iterators(使用 string::cbegin()):

drive_path = std::string(path.cbegin(), r.begin());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2017-03-10
    相关资源
    最近更新 更多