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

标签 c++ parameters constructor

我有一个具有许多属性的结构/类,其中一个是主要属性。在构造此类的实例时,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/

相关文章:

c++ - SQLite - 另存为?

javascript - 以零数字开头的参数无法正确传递给 JavaScript 函数

java - QueryParameterException 即使一切似乎都被正确命名

python - 函数参数 Python 的多个默认值

具有非默认构造函数的 C++ 继承

c++ - move 和转发案例使用

c++ - 如何在运行时将参数放入函数中?

c++ - 为什么这个汇编代码更快?

c# - 我对 COM 和跨平台兼容性感到困惑

delphi - 我需要将 "inherited"行添加到记录构造函数中吗?