简体   繁体   English

常规/动态类型作为参数C / C ++

[英]General/Dynamic type as a parameter C/C++

I would like to achieve something like this: 我想实现以下目标:

class Test {
    Test() {}
    Test(generalObject a){
       // do something
    }
}

int main(){
    Test a = 5;
    Test b = "A";
    Test c = true;
}

Is this even possible with the solution I would like? 我想要的解决方案甚至有可能吗?

generalObject can be any other type as well, doesn't need to be class type. generalObject也可以是任何其他类型,而不必是类类型。 Of course I know that I can write like different operator for different type, but I would like to skip that phase. 当然,我知道我可以为不同的类型编写不同的运算符,但是我想跳过该阶段。

These: 这些:

Test a = 5;
Test b = "A";
Test c = true;
Test d = Test();

are not assignments, they are copy initializations . 不是赋值,它们是副本初始化 Compiler looks for a non-explicit constructor (including copy constructor for the last statement). 编译器将查找非显式构造函数(包括最后一条语句的副本构造函数)。 operator= is not needed in your code. 您的代码中不需要operator=

As you're not doing anything with the passed arguments, this comes up (only to get your code to compile): 由于您不对传递的参数做任何事情,因此出现了此问题(仅是为了使您的代码得以编译):

struct Test {
    Test() = default;

    template <typename T> // a constructor template
    Test(T const&) {}
};

C++ does not have a base class for every type, you need to use constructor template to instantiate a constructor for every type that's required - at compile time. C ++并非每种类型都有一个基类,您需要使用构造函数模板为所需的每种类型实例化构造函数-在编译时。


This gets more complicated if you actually want to store the argument inside Test (template specializations for array types, convenience function template make_test , etc...). 如果您实际上想将参数存储在Test内部(数组类型的模板专长,便捷函数模板make_test等),则情况将变得更加复杂。 I guess this is your entry to templates, so you might want to go step by step. 我想这是您进入模板的入口,因此您可能需要逐步进行。

In you example you dont need assignment operator, but converting constructor which will accept various types: 在您的示例中,您不需要赋值运算符,但可以转换构造函数 ,该构造函数将接受各种类型:

class Test{
public:    
    Test(){}

    Test(int r){}
    Test(const char* r){}
    Test(bool r){}
    Test(const Test& r){}
};
int main(){
    Test a = 5;
    Test b = "A";
    Test c = true;
    Test d = Test();
}

But it makes sense to implement also assignment operator. 但是也可以实现赋值运算符。 If you really need any type then use templates, your constructor will look like below: 如果您确实需要任何类型,请使用模板,构造函数如下所示:

    template<typename T>
    Test(const T& t){}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM