On 3ÔÂ10ÈÕ, ÏÂÎç9ʱ49·Ö, "Alf P. Steinbach" <a...@start.nowrote:
* Wayne Shu:
There is a problem.
Is there?
e.g.
template <typename T>
class foo
{
public:
foo();
~foo();
private:
static size_t bar;
};
template <typename T>
size_t foo<T>::bar = 0;
template <typename T>
foo<T>::foo()
{
++bar; // (1)
}
template <typename T>
foo<T>::~foo()
{
--bar; // (2)
}
Note the place (1), (2), it can be replaced with
++foo<T>::bar;
--foo<T>::bar;
The qualified name and unqualified name are all OK,
and most c++ book use the qualified name preferable.
I know that it is something related with the name lookup.
but I don't know the details.
Does it have somebody explain it for me??
It may have been just a basic instinct or style on the part of the
authors, it may be that you've misunderstood the context, that the
books' examples haven't been exactly equivalent to the code you present.
The book is "C++ Template The Complete Guide",
and the example is the section 16.3 "The Curiously Recurring Template
Pattern"
The complete code is
// inherit/objectcounter.hpp
template <typename CountedType>
class ObjectCounter {
private:
static size_t count; // number of existing objects
protected:
// default constructor
ObjectCounter() {
++ObjectCounter<CountedType>::count;
}
// copy constructor
ObjectCounter (ObjectCounter<CountedTypeconst&) {
++ObjectCounter<CountedType>::count;
}
// destructor
~ObjectCounter() {
--ObjectCounter<CountedType>::count;
}
public:
// return number of existing objects:
static size_t live() {
return ObjectCounter<CountedType>::count;
}
};
// initialize counter with zero
template <typename CountedType>
size_t ObjectCounter<CountedType>::count = 0;
// inherit/testcounter.cpp
#include "objectcounter.hpp"
#include <iostream>
template <typename CharT>
class MyString : public ObjectCounter<MyString<CharT {
//...
};
int main()
{
MyString<chars1, s2;
MyString<wchar_tws;
std::cout << "number of MyString<char>: "
<< MyString<char>::live() << std::endl;
std::cout << "number of MyString<wchar_t>: "
<< ws.live() << std::endl;
}
You don't say which books or which examples that befuddle you.
Without that information further discussion would be just as much pure
speculation as this short reply. ;-)
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?- Òþ²Ø±»ÒýÓÃÎÄ×Ö -
- ÏÔʾÒýÓõÄÎÄ×Ö -