[英]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::variant
或std::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.