1

I was working on a print() function in C++ and was wondering:

template <typename BaseType>
void print(BaseType data, bool newline = false, bool raw = false) {
    // Standard > C Out
    std::cout << data;

    /* Logic
            If
                Newline is true.
    */
    if (newline)
        std::cout << std::endl;
};

What if this same function could react differently to arrays and print out each individual member of the array rather than give back a value like 0x22fe30?

Something like:

print("Hello, World!"); // prints "Hello, World!"
print(array); // prints "[1, 0, 1]"

I'm only doing this for fun to see how far my skills in C++ really are and would appreciate any helpful answer. Thanks.

  • What you're looking for is called "specialization". – Sam Varshavchik Oct 29 '17 at 02:07
  • 1
    Be careful what you wish for. `"Hello, World!"` is an array of type `char[14]` – Igor Tandetnik Oct 29 '17 at 02:07
  • How would that work out? I'm new to C++ and self-taught, this is the first time I've heard of Specialization. – John Akinola Oct 29 '17 at 02:13
  • True. I didn't think about character arrays. – John Akinola Oct 29 '17 at 02:14
  • Self-taught is cool, but make sure you [have some good support](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). C++ is a very hard language to pick up without a good reference library. – user4581301 Oct 29 '17 at 02:16
  • Note, you also have to pass the size of the array. When printing a character array, the size of array can be determined by the null-terminator. But when printing array of integers, the common way to know the size is to pass the size as a separate parameter. Such a generalized print function may not be all that useful (except for learning purposes). You can make your own container, example `myvector` derived from `std::vector` and add print capabilities to it instead. – Barmak Shemirani Oct 29 '17 at 02:27
  • 1
    I would avoid redundant comments. Everyone who knows C++ already knows that `if(newline)` means "If newline is true"; your comment is just serving as clutter. In this case it would be better without the comments entirely; in general, comments should add some explanation that is not immediately apparent just from the code; e.g. the rationale for why you chose to do the thing you're doing. – M.M Oct 29 '17 at 03:31
  • yes, you're right. – John Akinola Oct 29 '17 at 07:14

1 Answers1

0

You can iterate into array and print them out:

const int arr [ 3 ] = { 5, 6, 7 };

for ( int i = 0; i < 3; i++ )

    std::cout << arr [ i ] << std::endl;
lambda
  • 39
  • 5