C ++如何传递这样的结构?

时间:2015-08-17 01:36:59

标签: c++

我想通过这样的结构:

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

这样的函数:

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';
}

我知道myfunc()必须是......错了,我怎么能正确地做到这一点?非常感谢!

#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;
}

1 个答案:

答案 0 :(得分:3)

您有一个不必要的typename

这是更新的代码

#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