How do I set parameter default values that rely on other parameters?

前端 未结 2 1921
臣服心动
臣服心动 2021-01-07 10:23

The following code compiles and works as expected.

#include 

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

int main(){
    std::vect         


        
2条回答
  •  -上瘾入骨i
    2021-01-07 11:12

    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& vec, const size_t size)
    {
       ...
    }
    
    void function(const std::vector& vec)
    {
       function(vec, vec.size());
    }
    

提交回复
热议问题