Dilawar
Dilawar

Reputation: 5645

Vector of pointers to struct

Following program looks pretty OK to me. But I can not get it compiled.

#include    <iostream>
#include    <vector>
using namespace std;

int main()
{
    struct a
    {
        int i;
        int j;
    };


    std::vector<a*> vecA;

    a* pA = new a;

    pA->i = 4;
    pA->j = 9;

    vecA.push_back(pA);

    return 0;
}

It generates following error.

struct_update.cc: In function ‘int main()’:
struct_update.cc:32:19: error: template argument for ‘template<class _Alloc> class std::allocator’ uses local type ‘main()::a*’
struct_update.cc:32:19: error:   trying to instantiate ‘template<class _Alloc> class std::allocator’
struct_update.cc:32:19: error: template argument 2 is invalid
struct_update.cc:32:25: error: invalid type in declaration before ‘;’ token
struct_update.cc:39:10: error: request for member ‘push_back’ in ‘vecA’, which is of non-class type ‘int’

Upvotes: 7

Views: 16329

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283883

This isn't true anymore in the new C++11 standard, but current compilers don't fully implement it yet.

A local type can't be a template parameter. Move your structure definition above main, and everything will work.

Or update your compiler to one that supports this part of C++11.

Here's the restriction from C++03 section 14.3.1 ([temp.arg.type]), which is removed in C++11:

A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.

Upvotes: 13

parapura rajkumar
parapura rajkumar

Reputation: 24423

Move the structure definition out of main function.

   struct a
    {
        int i;
        int j;
    };

int main()
{

    std::vector<a*> vecA;

    a* pA = new a;

    pA->i = 4;
    pA->j = 9;

    vecA.push_back(pA);

In C++03 you cannot do this

A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.

In C++11 i think you can according to the standard. Even though my Visual Studio 11 compiler refuses to allow it

Upvotes: 7

Related Questions