boost::optional vector pass by reference as default parameter

4.7k views Asked by At
boost::optional<std::vector<std::wstring>> filePath;

If I have the above boost optional vector is it possible to then pass this by reference and as an optional parameter?

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

Could I pass filePath as a default parameter and by reference at the same time?

3

There are 3 answers

2
dau_sama On

What you are doing is legal, but you can't pass a reference as a default parameter. Should you want that, you'd need to pass a value, or the file path wrapped around another boost::optional.

0
sehe On

You can use an optional reference:

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

Prints

3 elements
default parameter
2
m.s. On

Either put the reference inside the boost optional (boost::optional<std::vector<std::wstring>& >) as @sehe wrote, or use a const reference:

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

}

live example: http://coliru.stacked-crooked.com/a/324e31e1854fadb9

In C++ you are not allowed to bind a temporary to a non-const reference. In this case, the default value is the temporary so you need a const reference.