A template class and a normal class:
template <typename Type>
class Holder
{
public:
Holder(const Type& value) : held_(value)
{
cout << "Holder(const Type& value)" << endl;
}
Type& Ref() { return held_; }
private:
Type held_;
};
class Animal
{
public:
Animal(const Animal& rhs) { cout << "Animal(const Animal& rhs)" << endl; }
Animal() { cout << "Animal()" << endl; }
~Animal() { cout << "~Animal" << endl; }
void Print() const { cout << "Animal::Print()" << endl; }
};
Then I want to instantiate a Holder<Animal>
with this statement Holder<Animal> a(Animal());
, however, it fails. I mean Animal()
is not treated as a temporary object. And this statement doesn't call Holder
's constructor.
If someone could explain? I'm not clear. I'm guessing a
becomes a type here. Then, I use Holder<Animal> a = Holder<Animal>(Animal());
, it works well. So, there are some cases here:
Holder<Animal> a(Animal()); a.Ref().Print(); // error
Holder<Animal> a = Holder<Animal>(Animal()); a.Ref().Print(); // ok
Holder<int> b(4); b.Ref() = 10; cout << b.Ref() << endl; //ok
Can explain? I'm just a little confused with the first statement. And the error information this statement causes:
GCC4.7.2
: error: request for member 'Ref' in 'a', which is of non-class type 'Holder<Animal>(Animal (*)())'
VS10
: error C2228: left of '.Ref' must have class/struct/union
, error C2228: left of '.Print' must have class/struct/union
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…