Re: template type only known at runtime
On 18 nov, 08:51, Ralf Goertz
<r_goe...@expires-2006-11-30.arcornews.de> 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:
-----
#include <string>
template <class T> class foo {
T x;
public:
void do_something_depending_on_type_of_T(){
...
};
}
int main(int argc, char *argv[]) {
if (argc==1) //default type string should be used
foo<std::string> bar;
else //use class int
foo<int> bar;
bar.do_something_depending_on_type_of_T();
return 0;
}
Template based code is constructed at compile time (static
polymorphism). If you need dynamic polymorphism use virtual functions.
However, your code has a general C++ problem (not specific to
templates). The line bar.do_something_depending_on_type_of_T(); will
generate an error because bar is undefined. This would happen even if
bar was not a template.
I don't know if this is the best design for you. But the closest I can
get to it is through template specialization:
emplate <class T> class foo
{
public:
void do_something()
{} //You don't need trailing semi-colon here.
}; //You need it here though.
template <> class foo<std::string>
{
public:
void do_something()
{ /*Implementation for string */ }
};
template <> class foo<int>
{
public:
void do_something()
{ /*Implementation for int */ }
};
int main(int argc, char *argv[])
{
foo<std::string> stringBar;
foo<int> intBar;
if (argc==1)
stringBar.do_something();
else
intBar.do_something();
return 0;
}
--
Leandro T. C. Melo