Reg. Function Templates

V

VSP

Hi,

In the following code, we have created a template function,
We expected the output to display "A::A()" and "B::B()" but we are getting
both as "B::B()".

class A
{
public:
A()
{
cout<<endl<<"A::A()";
}
};

class B
{
public:
B()
{
cout<<endl<<"B::B()";
}
};

template<class T>
void func()
{
T t;
}

int main(int argc, char* argv[])
{
func<A>();
func<B>();
return 0;
}

Please clarify.
Compiler Used: VC++ 6.0

Regards,
VSP
 
J

Jim Langston

VSP said:
Hi,

In the following code, we have created a template function,
We expected the output to display "A::A()" and "B::B()" but we are getting
both as "B::B()".

class A
{
public:
A()
{
cout<<endl<<"A::A()";
}
};

class B
{
public:
B()
{
cout<<endl<<"B::B()";
}
};

template<class T>
void func()
{
T t;
}

int main(int argc, char* argv[])
{
func<A>();
func<B>();
return 0;
}

Please clarify.
Compiler Used: VC++ 6.0

In VC++ .net 2003 the output is the expected

A::A()
B::B()

Of course after I included <iostream> and changed cout and endl to std::cout
and std::endl.

Try a fresh build. If that doesn't work, it's a bug in VC++ 6.0. 6.0 is
fairly old, prestandard and has a few bugs. You definately need to upgrade.
 
B

Bo Persson

Jim Langston wrote:
:: ::: Hi,
:::
::: In the following code, we have created a template function,
::: We expected the output to display "A::A()" and "B::B()" but we
::: are getting both as "B::B()".
:::
::: class A
::: {
::: public:
::: A()
::: {
::: cout<<endl<<"A::A()";
::: }
::: };
:::
::: class B
::: {
::: public:
::: B()
::: {
::: cout<<endl<<"B::B()";
::: }
::: };
:::
::: template<class T>
::: void func()
::: {
::: T t;
::: }
:::
::: int main(int argc, char* argv[])
::: {
::: func<A>();
::: func<B>();
::: return 0;
::: }
:::
::: Please clarify.
::: Compiler Used: VC++ 6.0
::
:: In VC++ .net 2003 the output is the expected
::
:: A::A()
:: B::B()
::
:: Of course after I included <iostream> and changed cout and endl to
:: std::cout and std::endl.
::
:: Try a fresh build. If that doesn't work, it's a bug in VC++ 6.0.
:: 6.0 is fairly old, prestandard and has a few bugs. You definately
:: need to upgrade.

Yes, this is a known bug in VC6. The compiler uses function
parameters, but not template parameters, in the function signature.
This fools the linker into believing that there is only one func().


If you change the function to

template<class T>
void func(const T* = 0)
{
T t;
}

it will work as it should.

If you try to learn C++, the free Visual C++ Express (VC8) is a much
better choice.


Bo Persson
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top