slavinger@yahoo.com wrote:[color=blue]
> I was attempting do the following (in VC++):
>
> #define AGE 1
> #define NAME 2
>
> template<class T> T getInfo(int what)
> {
> int age = 20;
> string name = "whatever";
>
> if (what == AGE)
> return age;
> else if (what == NAME)
> return name;
> }
>
> The idea is that main() can get both kinds of info by calling a single
> function, for instance "cout << getInfo(NAME);" I was looking to
> implement this function inside a class that has many different types of
> private data. The compiler is complaining that it can't deduce the
> data type of T. I can see why it's complaining, so I'm wondering: is
> there a way to do something like this in C++? Thanks.[/color]
Well, no, actually. If the argument will be known at compile time,
you don't need a template, you just need a bunch of functions, like
std::string getName();
int getAge();
But if the argument ('what') is not known at compile time, then you
won't be able to do what you think you need:
cout << somefunctionreturningunknowntype(what);
is *not* going to compile for the same reason as
whattypetousehere var = somefunctionreturningunknowntype(what);
C++ is a statically typed language with some features allowing the use
of run-time polymorphism, which, incidentally, still requires some kind
of common type binding all derived types together. If your return values
are as unrelated as 'std::string' and 'int', there is no polymorphism to
speak of.
V