Search code examples
c++c++11default-parameters

Is it possible to know if the parameter was defaulted


Caution: This problem is limited to MSVS

I have this function signature:

void do_somthing(std::vector<foo>&  bar={});

Is it possible to differ between those two calls for the function:

First:

do_something()

Second:

std::vector<foo> v;
do_something(v);

In other words, I want something like:

void do_somthing(std::vector<foo>&  bar={}){
    if(/* bar was defaulted*/){

    }
    else{

    }
}

EDIT: The actual code:

template<class Tinput_iterator>
            Tmodel perform_fitting(Tinput_iterator begin_data, Tinput_iterator end_data, std::vector<Tpoint>& inliers = {});

Solution

  • I have this function signature:

    void do_somthing(std::vector<foo>&  bar=std::vector<foo>{});
    

    This cannot compile, except with dangerous non-standard compiler settings you should stay away from.

    In particular, Visual C++ allows this if /Za is not specified, but with /W4 still produces a warning like this:

    stackoverflow.cpp(6): warning C4239: nonstandard extension used: 'default argument': conversion from 'std::vector<foo,std::allocator<_Ty>>' to 'std::vector<foo,
    std::allocator<_Ty>> &'
            with
            [
                _Ty=foo
            ]
    stackoverflow.cpp(6): note: A non-const reference may only be bound to an lvalue
    
    void do_somthing(std::vector<foo>&  bar=std::vector<foo>{}){
        if(/* bar was defaulted*/){
    
        }
        else{
    
        }
    }
    

    Even if we assume that you actually included the missing const to make the code compile, the answer would be: no, it is not possible to know if bar was defaulted.

    Whatever you plan to do here, you have to find a completely different solution.