Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

a template clads static element

21 views
Skip to first unread message

asetof...@gmail.com

unread,
May 19, 2015, 12:55:36 PM5/19/15
to
If i have:
template<class T> class per{
// ....
per(){++v; /*...*/ }
static int v;
};

How access and define v?

v would be a global value only 32
Bit
One for the class
that can be accessed only from
function of 'per' and objects of
'per' type...

asetof...@gmail.com

unread,
May 19, 2015, 12:59:24 PM5/19/15
to
Class in subject line...
It seems this compile:
template<class T> class per{
// ....
per(){++v; /*...*/ }
static int v;
};
int per<int>::v=0;

Would be right even if type T
is different from int?

Victor Bazarov

unread,
May 19, 2015, 1:06:29 PM5/19/15
to
No. You need to define it as a template, if you want every 'per'
instantiation to have it:

template<class T> int per<T>::v = 0;

And do it in the header. The compiler/linker will take care of creating
only one object per instantiation.

V
--
I do not respond to top-posted replies, please don't ask

asetof...@gmail.com

unread,
May 19, 2015, 1:17:35 PM5/19/15
to
Thank you

asetof...@gmail.com

unread,
May 20, 2015, 2:35:43 AM5/20/15
to
Yes but if i have
template<class T> class per{
// ....
per(){++v; /*...*/ }
static int v;
};

int per<int>::v=0;

I can access v from function g below

void g(void)
{...
per<int>::v=1;
}

If instead one has
template<class T> int per<T>::v=0;
How g would access v?

Wouter van Ooijen

unread,
May 20, 2015, 2:44:04 AM5/20/15
to
asetof...@gmail.com schreef op 20-May-15 om 8:35 AM:
'how' is a strange question in this context. It does. The line

template<class T> int per<T>::v=0;

Defines a v for each instantiation of per, hence when you use per<int>
the compiler will define per<int>::v.

Wouter

0 new messages