1

The following code compiles and works as expected.

#include <vector>

void function(std::vector<int> vec, int size=1);

int main(){
    std::vector<int> vec = {1,2,3};
    function(vec);
}


void function(std::vector<int> vec, int size){
    //code..
    return;
}

However, I would like the size parameter's default value to be deduced based on a previous parameter. So for example:

void function(std::vector<int> vec, int size=vec.size());

But this however results in:
error: local variable ‘vec’ may not appear in this context

Which doesn't surprise me; I assume it needs to know the default value at compile time. So do I make the function templated? How would I make the function templated in such a way that the parameter is still an int, and the vector, is still a vector of ints, and the size parameter is deduced to be the passed in vector's size by default.

I would not like to have to pass in the size of the vector during the function call.

1
  • I assume it needs to know the default value at compile time, that is not true, actually you can using global variable as default argument, but because the function parameter evaluation order are not defined, C++ standard explicitly prohibit access parameter when evaluate default value. Commented Nov 7, 2013 at 9:55

2 Answers 2

4

If you truly want a function with a size parameter, and want the size to default to the vector size (instead of just getting it as a local variable), then you could solve this with two functions. One taking just the vector, and one taking the vector and the size (without default). Then the one-argument function can just call the second.

So

void function(const std::vector<int>& vec, const size_t size)
{
   ...
}

void function(const std::vector<int>& vec)
{
   function(vec, vec.size());
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's probably the solution I want. Especially because I'm making std::function objects, and this is the only function that requires a second parameter.
1

Why do you need second parameter if it based on the first?

    void function(std::vector<int> vec ){
        size_t size = vec.size();
        //code..
        return;
    }

Isn't it easier?

2 Comments

Because he wants the caller to specify a value different than the default size.
Yeah, the function is recursive, with a changing "size value" each time. I just wanted to avoid passing it in on the root call since it's always going to be vec.size()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.