Reputation: 13
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;
Upvotes: 1
Views: 114
Reputation: 11
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);
}
Upvotes: 1
Reputation: 137315
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).
Upvotes: 4