提供Function参数的最佳方法

时间:2016-01-11 08:58:33

标签: c++

我有一个Api,它将两个struct作为参数

struct bundle{
int a;
int b;
int c;
};

void func(const bundle& startBundle, const bundle& endBundle);

此外,我必须编写另一个具有相同要求的API,而不是在bundle结构中的int a,它应该是double。

我可以编写2个结构(1表示int,1表示双重)但似乎不好,如果我使用结构,则函数有太多参数(3个开头为agruments,3个结尾为agrument)。 请提出一些正确的方法来解决这个问题。

另外如果我必须使用endBundle的默认参数,我该如何使用它?

1 个答案:

答案 0 :(得分:8)

您可以将bundle设为模板:

template <typename T>
struct bundle {
    T a;
    T b;
    T c;
};

void func(const bundle<int>& startBundle, const bundle<int>& endBundle); 

或者您可以使用std::array

using IntBundle = std::array<int, 3>;
using DoubleBundle = std::array<double, 3>;
void func(const IntBundle& startBundle, const IntBundle& endBundle); 

如果您想在同一个捆绑包中使用不同的类型,则可以使用std::tuple

using IntBundle = std::tuple<int,int,int>;
using OtherBundle = std::tuple<float,int,int>; 

或者让bundle获取三个模板参数:

template <typename A, typename B, typename C>
struct bundle {
    A a;
    B b;
    C c;
};