0

I wanna pass a struct like this:

template<typename T>
struct mystruct{
    T a;
    T b;
    typename std::vector<T> v1;
};

to a function like this:

template<typename T>
inline void myfunc(const typename mystruct<T> &struct1){
    std::cout<<struct1.a<<'\t'
             <<struct2.b<<'\n';
    for(int i =0; i<struct1.v1.size(); i++)
        std::cout<<struct1.v1[i]<<'\n';
}

I know myfunc() must be sth. wrong, how can I correctly do this? Many thanks!

#include <iostream>
#include <vector>

int main(){
    mystruct<float> strc1;
    strc1.a = 1.0;
    strc1.b = 2.0;
    strc1.v1.push_back(1.0);
    strc1.v1.push_back(2.0);
    myfunc(strc1);
    return 0;
}
Kylxyz
  • 29
  • 9
  • 2
    You are using "typename" too many times, you should only use "typename" in the phrase *template* here, not for declaring a member variable or an argument to a function – Chris Beck Aug 17 '15 at 01:38
  • I am sorry buddy@Chris Beck, I cannot quite catch you, would you please explain it more clearly? – Kylxyz Aug 17 '15 at 01:42
  • what is the problem? just pass it like other normal function – Bryan Chen Aug 17 '15 at 01:44
  • 1
    @Kylxyz it means read this: ["Where and why do I have to put the 'template' and 'typename' keywords?"](https://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords). – WhozCraig Aug 17 '15 at 01:48
  • my compiler does not allow this , i am using `g++ -std=c++0x ...` my g++ is 4.8.4 version. It shows me : expected primary-expression before ‘const’ – Kylxyz Aug 17 '15 at 01:50

1 Answers1

3

You have a unnecessary typename.

This is updated code that works

#include <iostream>
#include <vector>

template<typename T>
struct mystruct{
    T a;
    T b;
    typename std::vector<T> v1; // typename here is also not needed
};

template<typename T>
inline void myfunc(const /*-typename-*/ mystruct<T> &struct1){
    std::cout<<struct1.a<<'\t'
             <<struct1.b<<'\n';
    for(size_t i =0; i<struct1.v1.size(); i++)
        std::cout<<struct1.v1[i]<<'\n';
}

int main(){
    mystruct<float> strc1;
    strc1.a = 1.0;
    strc1.b = 2.0;
    strc1.v1.push_back(1.0);
    strc1.v1.push_back(2.0);
    myfunc(strc1);
    return 0;
}

Demo on Coliru

Bryan Chen
  • 45,816
  • 18
  • 112
  • 143