boost :: optional vector通过引用传递为默认参数

时间:2015-06-18 10:30:33

标签: c++ boost boost-optional

boost::optional<std::vector<std::wstring>> filePath;

如果我有上面的boost可选向量,那么可以通过引用传递它并作为可选参数吗?

Test(const boost::filesystem::path& targetPath, boost::optional<std::vector<std::wstring>> filePath = boost::none);

我可以将filePath作为默认参数并同时通过引用传递吗?

3 个答案:

答案 0 :(得分:3)

您可以使用可选参考:

请参阅http://www.boost.org/doc/libs/1_58_0/libs/optional/doc/html/boost_optional/optional_references.html

<强> Live On Coliru

#include <boost/optional.hpp>
#include <boost/filesystem.hpp>
#include <vector>
#include <iostream>

void Test(const boost::filesystem::path& targetPath,
          boost::optional<std::vector<std::wstring>& > filePath = boost::none) {
    if (filePath)
        std::cout << filePath->size() << " elements\n";
    else
        std::cout << "default parameter\n";
}

int main() {
    std::vector<std::wstring> path(3, L"bla");

    Test("blabla", path);
    Test("blabla");
}

打印

3 elements
default parameter

答案 1 :(得分:0)

您所做的是合法的,但您无法将引用作为默认参数传递。如果你想要,你需要传递一个值,或者包含另一个boost :: optional的文件路径。

答案 2 :(得分:0)

将引用置于boost可选(boost::optional<std::vector<std::wstring>& >)内,如@sehe所写,或使用 const 引用:

void Test(const boost::filesystem::path& targetPath,
          const boost::optional<std::vector<std::wstring> >& filePath = boost::none)
{

}

直播示例:http://coliru.stacked-crooked.com/a/324e31e1854fadb9

在C ++中,您不能bind a temporary to a non-const reference。在这种情况下,默认值是临时值,因此您需要一个const引用。