template with type=array?

This is a discussion on template with type=array? within the C++ Programming forums, part of the General Programming Boards category; I have this code: Code: #include <iostream> using namespace std; template <typename A> void doodle(A dod) { cout << "Size ...

  1. #1
    Registered User Mortissus's Avatar
    Join Date
    Dec 2004
    Location
    Brazil, Porto Alegre
    Posts
    152

    template with type=array?

    I have this code:
    Code:
    #include <iostream>
    
    using namespace std;
    
    template <typename A>
    void doodle(A dod)
    {
        cout << "Size of dod is " << sizeof(dod) << "." << endl;   
    }
    
    int main()
    {
        char dod[8];
        
        doodle(dod);   
        
        cin.get();
        
        return 0;
    }
    It prints "Size of dod is 4.", the size of a pointer. I wanted the template was instantiated with type char[8], not char*. Is it possible? I am using Gcc 3

    Thanks any help

  2. #2
    Tropical Coder Darryl's Avatar
    Join Date
    Mar 2005
    Location
    Cayman Islands
    Posts
    503
    Code:
    #include <iostream>
    
    using namespace std;
    
    template <typename A>
    void doodle(A& dod)
    {
        cout << "Size of dod is " << sizeof(dod) << "." << endl;   
    }
    
    int main()
    {
        char dod[8];
        
        doodle(dod);   
        
        cin.get();
        
        return 0;
    }

  3. #3
    Registered User Mortissus's Avatar
    Join Date
    Dec 2004
    Location
    Brazil, Porto Alegre
    Posts
    152
    Wow! Thanks so much!

    Er... could you explain it? The solution is so simple I almost feel an idiot.

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    6,245
    Passing an array to a function, as in your original code, actually passes a pointer to the first element. sizeof therefore yields the size of that pointer, rather than the size of the array.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Specialising a member function with a template template parameter
    By the4thamigo_uk in forum C++ Programming
    Replies: 10
    Last Post: 10-12-2007, 04:37 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. error: template with C linkage
    By michaels-r in forum C++ Programming
    Replies: 3
    Last Post: 05-17-2006, 08:11 AM
  4. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  5. oh me oh my hash maps up the wazoo
    By DarkDays in forum C++ Programming
    Replies: 5
    Last Post: 11-30-2001, 11:54 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21