Re: template type only known at runtime
Hendrik Schober wrote:
Ralf Goertz wrote:
Hi,
I want to do able to declare an object bar of a templated class foo
where the actual template type of foo is only know at runtime:
If the type is only known at run-time, you need run-time
polymorphy, which is done using virtual functions and
inheritance. However, that doesn't mean you can't use
templates at all:
class foo_base {
public: virtual void do_something_depending_on_type_of_T() = 0; };
virtual void do_something_depending_on_type_of_T() = 0;
};
template< typename T >
class foo : public foo_base {
public:
virtual void do_something_depending_on_type_of_T() {}
};
Actually, I just need two different types for the template,
foo<std::string> and foo<int>. The only difference is the id type I get
from a database, it can be either integer or char and is known only at
runtime. If it is numeric I still have to do some calculations with it
(so I can't just sql-cast it to char and use std::string in my program).
Also, the way of writing back the data to the db differs because of
quoting. "id" must be part of the class as I also need it for
std::map<T,double> within class foo. But wrapping it in another template
function as you also suggested seems to be the way to go.
Thanks for the ternary ?: suggestion in the other posting!
Ralf