使用参数获取其他人

Iss*_* T. 5 c++ parameters constructor

我有一个struct/class,它有许多属性,其中一个是principal.在构造此类的实例时,必须在参数中给出principal属性,但是可以提供或不提供任何其他属性.如果未将属性作为参数提供,则应从principal属性计算该属性.

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

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

Nik*_*iou 2

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

callFunction(param1=2, param3="hello")
Run Code Online (Sandbox Code Playgroud)

如果您拥有擦除键值对类型的映射作为成员,则可以在 C++ 中执行此操作:

map<string, ErasedType> _m; 
Run Code Online (Sandbox Code Playgroud)

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

我们暂时离开吧ErasedType。如果你有这样的成员,你可以写:

class MyClass
{
    map<string, ErasedType> _m;
public:
    MyClass(map<string, ErasedType> const& args) : _m(args) {}
};
Run Code Online (Sandbox Code Playgroud)

这样您只需指定所需的键并为它们分配特定的值。构造此类构造函数的输入的示例是

map<string, ErasedType> args = { {"arg1", 1}, {"arg1", 1.2} };
Run Code Online (Sandbox Code Playgroud)

然后访问特定值将采用如下成员函数:

    ErasedType get(string const& name) { return _m[name]; }
Run Code Online (Sandbox Code Playgroud)

现在在ErasedType. 最典型的方法是将其作为您保留的所有可能类型的联合:

union ErasedType { // this would be a variant type
    int n;
    double d;
    char c;
};
Run Code Online (Sandbox Code Playgroud)

第二个想法是让每个映射值都是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;
}
Run Code Online (Sandbox Code Playgroud)

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