Classes declared in templated functions

D

Dave Rahardja

Hi all,

If a class is declared inside a templated function, e.g.


template <typename> fn()
{
class A {};
static A a;
}


And I instantiate fn with the same typename twice, in two different
compilation units,

----
// a.cpp
void b();

int main()
{
fn<int>();
b();
}

----
// b.cpp

void b()
{
fn<int>(); // identical instantiation
}



Will the static member a be multiply defined at link time? I would think not,
as the two template instantiations have identical instantiation parameters,
and thus should correspond to a single instance. However, MSVC 2005 seems to
think otherwise.

In addition, I would guess that a /different/ instantiation of fn (e.g.
fn<double>()) will yield a /different/ instance of a. Am I right?

-dr
 
J

John Harrison

Dave said:
Hi all,

If a class is declared inside a templated function, e.g.


template <typename> fn()
{
class A {};
static A a;
}


And I instantiate fn with the same typename twice, in two different
compilation units,

----
// a.cpp
void b();

int main()
{
fn<int>();
b();
}

----
// b.cpp

void b()
{
fn<int>(); // identical instantiation
}



Will the static member a be multiply defined at link time? I would think not,
as the two template instantiations have identical instantiation parameters,
and thus should correspond to a single instance. However, MSVC 2005 seems to
think otherwise.

I would say you are right, however I can't reproduce the problem you
claim with MSVC 2005.
In addition, I would guess that a /different/ instantiation of fn (e.g.
fn<double>()) will yield a /different/ instance of a. Am I right?

I think you're right again.

john
 

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

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top