gpt4 book ai didi

c++ - 使用参数获取其他参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:39:27 26 4
gpt4 key购买 nike

我有一个具有许多属性的结构/类,其中一个是主要属性。在构造此类的实例时,principal 属性必须在参数中给出,但可以提供也可以不提供任何其他属性。当一个属性没有作为参数提供时,它应该从主要属性计算。

我不知道如何在不编写指数级数量的构造函数的情况下编写这样一个类;或者在每个构造函数之后使用 setter,它只有一个参数对应于主体属性。

我在这里给出了一个最适合我的例子。但这当然不能编译:

#include <cstdlib>
#include <iostream>

using namespace std;

struct StringInfo
{
string str;
int importance;

StringInfo(string strP, int importanceP = strP.length()):
str(strP), importance(importanceP){}

};

int main(int argc, char** argv) {
string test = "test";
StringInfo info(test);
cout << info.importance << endl;
}

你有更好的(非指数)解决方案吗?提前致谢。

最佳答案

你实际上想要一个类似于 Python 的可选参数的行为,例如:

callFunction(param1=2, param3="hello")

如果你有一个类型为删除键值对的映射作为成员,你可以在 C++ 中执行此操作:

map<string, ErasedType> _m; 

map 的键是一个带有成员描述的字符串(由您选择)。

现在让我们离开 ErasedType。如果你有这样的成员,你可以写:

class MyClass
{
map<string, ErasedType> _m;
public:
MyClass(map<string, ErasedType> const& args) : _m(args) {}
};

这样你就可以只指定你想要的键并为它们分配特定的值。为此类构造函数构造输入的示例是

map<string, ErasedType> args = { {"arg1", 1}, {"arg1", 1.2} };

然后访问特定值将采用这样的成员函数:

    ErasedType get(string const& name) { return _m[name]; }

现在在 ErasedType 上。最典型的方法是将它作为您保留的所有可能类型的 union :

union ErasedType { // this would be a variant type
int n;
double d;
char c;
};

第二个想法是让每个映射值都是 boost::any 容器的一个实例。第三个想法(更老派)是使用 void*

玩具实现

#include <map>
#include <string>
#include <iostream>
#include <boost/any.hpp>

using namespace std;
using boost::any_cast;

class OptionalMembers
{
map<string, boost::any> _m;
public:
OptionalMembers(map<string, boost::any> const& args) : _m(args)
{
// Here you would initialize only those members
// not specified in args with your default values
if (args.end() == args.find("argName")) {
// initialize it yourself
}
// same for the other members
}
template<typename T>
T get(string const& memberName) {
return any_cast<T>(_m[memberName]);
}
};

int main()
{
// say I want my OptionalMembers class to contain
// int argInt
// string argString
// and then more members that won't be given
// as arguments to the constuctor

std::string text("Hello!");
OptionalMembers object({ { "argInt", 1 }, { "argString", text } });

cout << object.get<int>("argInt") << endl;
cout << object.get<string>("argString") << endl;

return 0;
}

在前面的示例中,您可以随意拥有任意数量的“成员”,并在构造函数中随意指定每个成员

关于c++ - 使用参数获取其他参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24535881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com