1

I'm practicing a template example. Here's the code:

//template_practice.h
#pragma once

template<typename T, unsigned N> 
void print_arry(ostream &out,const T (&arry)[N]) 
{
    for (T* i = cbegin(arry); i != cend(arry); i++) 
    {
        out << *i << " ";
    }
    out << endl;
}

//main.cpp
#include "stdafx.h"
using namespace std;

int main()
{
    int test[10] = { 1,2,3,4,5,6,7,8,9,10 };
    print_arry<int, 10> (cout, test);

    getchar();
    return 0;
}

//stdafx.h
//... (library headers)
#include "template_practice.h"

There are many errors, including: "header stop not at file scope. And IntelliSense PCH file was not generated","'ostream': undeclared identifier", "expression preceding parentheses of apparent call must have function type"...

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Catiger3331
  • 611
  • 1
  • 6
  • 18

1 Answers1

1

Firstly, add #include <iostream> (for std::ostream and std::endl) and #include <iterator> (for std::cbegin and std::cend) in template_practice.h. And add std:: when use them. (BTW using namespace std; is not a good idea) .

Secondly, cbegin(arry); returns const T*, so change the type of i to const T*, or use auto instead; e.g. for (auto i = cbegin(arry); i != cend(arry); i++).

LIVE

songyuanyao
  • 169,198
  • 16
  • 310
  • 405