简体   繁体   中英

An std::vector storing itself in a template class

I am examining how template class work, and I come with the following error:

template <class T>
class B
{
    public:
    std::vector<B<T> > queue;
    B();
    ~B();
};

int main()
{

    class B<int> tempQ();
    class B<int> temp2Q();
    class B<int> store();
    store.queue.push_back(tempQ);
    store.queue.push_back(temp2Q);
}

It gives me an compiling error:

main.cpp:52:8: error: request for member 'queue' in 'store', which is of non-class type 'B<int>()'
main.cpp:52:8: error: request for member 'queue' in 'store', which is of non-class type 'B<int>()'

Can someone give me some clue?

Also inside the template class B will it make a difference between

std::vector<B<T> > queue; 

and

std::vector<B> queue;

You have two different problems. First, vexing parse:

class B<int> store();

declares a function called store taking no parameters and returning a B<int> , not a default-constructed variable. Just write B<int> store; or, in C++11, B<int> store{}; . The class is also redundant and should be omitted.

Second,

std::vector<B<T> > queue;

instantiates a standard library container with an incomplete type (the type of a class isn't complete until you hit the closing } of its definition), which is undefined behavior. Depending on the implementation, you may be able to get away with it, but you really shouldn't do it. There are non-standard containers (such as those in Boost's containers library ) that are guaranteed to support incomplete types - use those.

Also inside the template class B will it make a difference between

  std::vector<B<T> > queue; 

and

  std::vector<B> queue; 

No difference. Inside B 's definition, the <T> after B is implied when the context requires a type (as opposed to a template).

In your code, "class B tempQ();" doesn't mean declaring variable It's just declaring function.

here is solution..

template <class T>
class B
{
    public:
    std::vector<B<T>> queue;
    B() {};
    ~B() {};
};

int main()
{
    B<int> tempQ;
    B<int> temp2Q;
    B<int> store;
    store.queue.push_back(tempQ);
    store.queue.push_back(temp2Q);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM