简体   繁体   English

根据传递给构造函数的参数,C++ 方法是否可以具有不同的返回类型?

[英]Can a C++ method have different return types depending on parameters passed to the constructor?

I have a template class in C++ that has a method that in theory should return a T (specific type) if a certain parameter is 1 (this parameter is not known until an object is constructed), and if the parameter is greater than 1 another instantiation of the class should be returned.我在 C++ 中有一个模板类,它有一个方法,如果某个参数为 1(在构造对象之前不知道该参数),并且如果该参数大于 1,则理论上应该返回 T(特定类型)应该返回类的实例化。 Is there any easy way to do this?有什么简单的方法可以做到这一点吗?

Consider: You're assigning the return value of that function to some auto variable.考虑:您正在将该函数的返回值分配给某个auto变量。 The compiler needs to be able to decide what type that variable has to be... at compile time .编译器需要能够决定该变量必须是什么类型......在编译时

So no, there is no way to do it.所以不,没有办法做到这一点。 You can use eg std::variant or std::any as return type, but you can't change return type through any runtime mechanics.您可以使用例如std::variantstd::any作为返回类型,但您不能通过任何运行时机制更改返回类型。

parameter is not known until an object is constructed..在构造对象之前,参数是未知的。

answer is答案是
Yes if above meant in static way是的,如果上面的意思是静态的
No if above meant in dynamic way否,如果以上表示动态方式

No code given above meant no useful way上面没有给出代码意味着没有有用的方法

(Sorry, cannot comment on anything yet) (抱歉,目前无法评论任何内容)

You are not able to have one function that has different types of returns (would not fit the technical definition of a function anymore), but if you are able to check the parameter that you say might be == 1 or > 1 you could probably make a call to one of two different methods, each performing your desired operation for their respective cases.您无法拥有一个具有不同类型返回值的函数(不再符合函数的技术定义),但是如果您能够检查您所说的参数可能是== 1> 1您可能可以调用两种不同方法中的一种,每种方法都针对各自的情况执行所需的操作。

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

相关问题 在 C++ 中,如何使构造函数可以具有不同类型的参数? - In C++, how to make it such that the constructor can have different types of arguments? C++ 如何根据作为输入传递的参数调用一个或另一个构造函数? - C++ How can I call one constructor or the other depending on the parameters passed as input? 在C ++中,如何根据类中的参数返回不同的泛型类型? - In C++, how to return different generic types depending on argument in a class? C ++模板返回具有相同参数的不同类型 - C++ Template to return different types with same parameters C ++虚拟方法返回不同的派生类型 - C++ Virtual Method return different derived types C++:模板化具有不同返回类型的虚方法 - C++: Templating a virtual method with different return types C ++:不同类型模板函数的自定义返回值(方法) - C++: Custom return value for different types of template function (method) 可以具有 3 种不同数据类型 C++ 的向量 - Vector that can have 3 different data types C++ C++ - 可以返回不同类型的模板函数? - C++ - Template function that can return different types? 使用初始化列表时检查传递给构造函数的参数-C ++ - Check parameters passed to constructor when using initialization lists - C++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM