如何设置依赖于其他参数的参数默认值? [英] How do I set parameter default values that rely on other parameters?

查看:277
本文介绍了如何设置依赖于其他参数的参数默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码按预期编译和工作。

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;
}

但是,我想要size参数的默认值,上一个参数。例如:

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());

但是这会导致:

vec'可能不会出现在此上下文中

我认为它需要知道编译时的默认值。那么我要使函数模板化吗?我将如何使函数模板化,使得参数仍然是一个int,并且向量,仍然是一个ints的向量,并且size参数被推导为默认向量的大小传递。

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.

推荐答案

如果你真的想要一个带有size参数的函数,并且想要的大小默认为向量大小(而不是只是把它作为一个局部变量),那么你可以用 two 功能。一个采用向量,一个采用向量和大小(没有默认)。

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.

因此

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

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

这篇关于如何设置依赖于其他参数的参数默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆