How to write a template function that takes an array and an int specifying array size

前端 未结 2 1128
你的背包
你的背包 2021-01-18 22:12

For a university exercise, I have been asked to write a template function \"print();\", which takes two arguments, 1: an array of a generic type, and 2: an int specifying t

相关标签:
2条回答
  • 2021-01-18 22:30

    The correct way to write it is

    Live On Coliru

    #include <iostream>
    
    template <typename T, size_t size> void print(const T (&array)[size])
    {
        for(size_t i = 0; i < size; ++i)
            std::cout << array[i] << " ";
    }
    
    int main() {
        int arr[] = { 1,2,3,4,99};
    
        print(arr);
    }
    

    Prints

    1 2 3 4 99
    
    0 讨论(0)
  • 2021-01-18 22:48

    If you want to pass the array by reference, you could

    template <typename T, size_t SIZE>
    void print(const T(&array)[SIZE])
    {
        for (size_t i = 0; i < SIZE; i++)
            std::cout << array[i] << " ";
    }
    

    and then, e.g.

    int x[] = {1, 2, 3};
    print(x);
    

    LIVE

    Otherwise, you can pass it by pointer, note that the array will decay to pointer, and you have to guarantee the correctness of SIZE being passed.

    template <typename T>
    void print(const T array[], size_t SIZE)
    {
        for(size_t i = 0; i < SIZE; i++)
            std::cout << array[i] << " ";
    }
    

    and then, e.g.

    int x[] = {1, 2, 3};
    print(x, sizeof(x) / sizeof(int));
    

    LIVE

    0 讨论(0)
提交回复
热议问题