C++ function that conditionally returns different types -
i'm attempting write template function return different types based on string passed in.
template<typename t> t test(string type) { int integer = 42; float floateger = 42.42; if (type == "int") return integer; if (type == "float") return floateger; } int main() { int integer = test("int"); cout << "integer: " << integer << endl; }
when run following error:
error: no matching function call 'test(const char [4])
how can implement such thing?
my end goal write function return objects of different classes depending on string passed it. know isn't right approach @ all. correct way this?
you can't that, @ least not way.
in order able return different types have first return reference , second possible returned types have inherit declared return type.
for example:
class base { }; class derived1 : public base { }; class derived2 : public base { }; base& func(string type) { static derived1 d1; static derived2 d2; if( type == "derived1" ) return d1; if( type == "derived2" ) return d2; //etc }
Comments
Post a Comment