Using template

Pardon me for not quoting the code. I can't seem to quote it. Previewing the message also doesn't help.

As you can see, I tried using template but it doesn't seem to work right. I tried to get the size of a table using sizeof() but the result is not the same when I do it inside and outside the main function.

#include <iostream>
using namespace std;

template <class T>
int ArraySize(T Table[])
{
cout << sizeof(Table);
cout << sizeof(*Table);
cout <<endl;
return 0;
}

int main()
{
string Commands[] = {"Library","Register"};

ArraySize(Commands);
cout << sizeof(Commands);
cout << sizeof(*Commands);

return 0;
}

Output:
44
84
In template <class T> int ArraySize(T Table[]) type of Table is 'pointer to T', sizeof(Table) == sizeof(pointer)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>

template < typename T, std::size_t N >
inline void print_sizeof_array( T (&alias_for_array)[N] ) // array passed by reference
{ std::cout << "size of the array: " << sizeof(alias_for_array) << '\n' ; }

template < typename T >
inline void print_sizeof_pointer( T pointer[] ) // pointer passed by value
{ std::cout << "  size of pointer: " << sizeof(pointer) << '\n' ; }

template < typename T, std::size_t N >
inline void print_num_elements_in_array( T (&)[N] ) // array passed by reference
{ std::cout << "     num_elements: " << N << '\n' ; }

int main()
{
    std::string commands[] = { "Library", "Register", "some other command" } ;

    std::cout << " size of commands: " << sizeof(commands) << '\n' ;
    print_sizeof_array(commands) ;

    std::string* pointer = commands ;
    std::cout << "\n  size of pointer: " << sizeof(pointer) << '\n' ;
    print_sizeof_pointer(commands) ;

    const std::size_t num_elements = sizeof(commands) / sizeof( *commands ) ;
    std::cout << "\n     num_elements: " << num_elements << '\n' ;
    print_num_elements_in_array(commands) ;
}

http://coliru.stacked-crooked.com/a/cf5c70a47d8d40b6
Pardon me for not quoting the code. I can't seem to quote it. Previewing the message also doesn't help.

The buttons doesn't work when creating a new topic. They only work when you edit or create new post. You can always surround your code in code tags manually.

[code] your code here [/code]
Topic archived. No new replies allowed.