c++ template to template parameter

后端 未结 2 336
余生分开走
余生分开走 2021-01-27 05:05

recently i was testing some c++ template codes and i found one mind-boggling error. According to my research on internet in particular stackoverflow, this code is completely val

2条回答
  •  醉话见心
    2021-01-27 05:25

    Expanding on chris' answer, the following compiles fine with both visual c++ 12.0 and g++ 4.7.2:

    #include 
    #include 
    using namespace std;
    
    template class C, class T, class U> void print(C& c)
    { (void) c; }
    
    void test() {
        vector v(5, "Yow!");
        print(v);
    }
    

    However, if you really just want to output the items of a container, why not do this instead:

    #include 
    #include 
    #include 
    using namespace std;
    
    template< class C >
    void print( C const& c )
    {
        for( auto const& item : c )
        {
            cout << item << endl;
        }
    }
    
    auto main() -> int
    {
        vector v(5, "Yow!");
        print(v);
    }
    

提交回复
热议问题