1
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?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
CodersSC
  • 710
  • 2
  • 13
  • 29

3 Answers3

4

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
user703016
  • 37,307
  • 8
  • 87
  • 112
sehe
  • 374,641
  • 47
  • 450
  • 633
0

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.

dau_sama
  • 4,247
  • 2
  • 23
  • 30
0

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.

Community
  • 1
  • 1
m.s.
  • 16,063
  • 7
  • 53
  • 88
  • This might work depending on the requirements of the OP. If the vector needs to be non-const he's out of luck. If he uses the `optional const&` then toplevel const doesn't add anything (because `optional` is just fine). You might want to add an explanation why `const&` works. – sehe Jun 18 '15 at 12:05
  • So you explain how you can bind a const-reference to a temporary by... saying you can not do something else. Mmm – sehe Jun 18 '15 at 12:46