一直在思考这些问题一段时间,但无法想出如何去做。
假设我有一个函数:
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/