具有无限可选参数和不同输入变量选择的 C++ 函数

标签 c++ function optional-parameters

一直在思考这些问题一段时间,但无法想出如何去做。

假设我有一个函数:

double sum( int param1 , double param2 , [ optional... ] )
{
     return param1 + param2;
}

现在我要

Q1:可选参数

Q2:无限数量的可选参数,无需全部声明。

Q3:在那些可选参数中使用 int 和 double 值

提前致谢:)

最佳答案

如果您熟悉 c++11 , 引入了一个名为 variadic templates 的新概念;从本质上讲,它允许人们创建像您提到的那样可以进行各种争论的功能。

声明此类函数的语法如下:

template <typename ... Types>
void someFunc(Types ...args) {}

另一种选择是使用 std::initializer_list连同 std::accumulate实现这一点,因为您已经知道您将使用的变量类型。使用您的程序的示例是这样的:

#include <iostream>
#include <initializer_list>
#include <numeric>
using namespace std;

double sum( initializer_list<double> vals ) {

    return accumulate(vals.begin(), vals.end(), 0.0);
}

int main() {
    // your code goes here
    cout << sum({2, 3, 4.6, 5, 6, 74.322, 1}) << endl;
    return 0;
}

关于具有无限可选参数和不同输入变量选择的 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20737307/

相关文章:

database - postgres脚本遇到语法错误: unexpected end of file

C++ - 如何不错过来自多个线程的多个通知?

c++ - 带有字符串和 bad_alloc 检查的构造函数

r - 将一组分类变量转换为单个向量的函数

C++ isMember 函数崩溃

c# - 有没有办法使用带有可选参数的 NUnit TestCase 属性

c++ - 在 char 数组包装类中实现 C++ setter 的正确方法是什么?

c++ - 为什么显式模板实例化会在存在外线虚拟时导致 weak-template-vtables 警告?

SQL Server : Optional variable in a stored procedure

c++ - 避免繁琐的可选参数