error: expected primary-expression before 'template' - what am I doing wrong?

#include <iostream>
#include <vector>

template<class T> struct A {
    A( const std::initializer_list<T> &list ) {
        for( template std::initializer_list<T>::iterator it = list.begin();
             it != list.end(); ++it ) {
            content.emplace( *it );
        }
    }
    ~A() {};
    std::vector<T> content;
};

int main() {
    A<int> a = A<int>( { 1, 2, 3, 4, 5 } );
    for( const int x : a.content ) {
        std::cout << x << " ";
    }
    return 0;
}

The code above reflects a problem I'm having. When I try compiling I get: error: expected primary-expression before 'template'... and error: 'it' was not declared in this scope for line 14 (the iterator for loop). I've tried some variation but I'm not getting anywhere with them. Does anyone got a clue on this issue? Thanks.

Upvotes: 1

Views: 730

Answers (2)

Greg M
Greg M

Reputation: 954

Take out template before your definition of it

for (std::initializer_list<T>::iterator it = list.begin();
            it != list.end(); ++it) {
            content.emplace(*it);
}

You are also using the emplace function wrong. Here is the documentation for emplace

Upvotes: 1

billz
billz

Reputation: 45410

  1. incorrect use of template keyword, suppose to be typename or just use auto

    for( template std::initializer_list::iterator it = list.begin(); ^^^^^^^^ it != list.end(); ++it ) {

  2. incorrect use [std::vector::emplace][1]

The fix is:

    for( auto it = list.begin(); it != list.end(); ++it ) 
    {
        content.emplace(content.end(), *it );
    }

or:

content.insert(content.end(), list);

Upvotes: 2

Related Questions