Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 views
in Technique[技术] by (71.8m points)

templates - Why this statement does not call the constructors - C++

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:

  1. Holder<Animal> a(Animal()); a.Ref().Print(); // error
  2. Holder<Animal> a = Holder<Animal>(Animal()); a.Ref().Print(); // ok
  3. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The statement Holder<Animal> a(Animal()); does not create a variable, but declares a function that returns a Holder<Animal> and that takes a function in parameter. It's usually called the most vexing parse, because of this ambiguity (that one would expect a variable rather than a function declaration).

Herb Sutter explains the different possible syntaxes here. In C++11, a possible solution is:

auto a = Holder<Animal> {};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...