Thread: templates

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    81
    Rep Power
    11

    templates


    I have the following function in the .h file
    template <typename T>
    void initialize(int, T []);
    I have implemented in the .cpp file as follows.

    template <typename T>
    void initialize(int num, T const &myArray)

    Now I have included the .h file in my main program.
    I try to call initialize.
    int num1;
    int nums[];
    initialize(num1,nums);
    I get the following error.
    undefined reference to `void initialize<int>(int, int*)'
    It works, if I don't use a template.
  2. #2
  3. not a fan of fascism (n00b)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Feb 2003
    Location
    ct
    Posts
    2,756
    Rep Power
    95
    try declaring and implementing to take a T * instead., like
    Code:
    void initialized(int num, T const *myArray);
  4. #3
  5. Left due to despotic ad-min
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2003
    Posts
    1,044
    Rep Power
    14
    There are a couple of strategies depending on your compiler. The most common is to include the template function body in the header file.

    An alternate method is to include the lines like the following at the end of the .cpp file

    template <> void initialize<int>(int, int[]); // version that takes int array
    template<> void initialize<double>(int, double[]); // version takes double array

    There is a third method, involving use of the "export" keyword but, unfortunately, I've yet to hear of a compiler that supports that fully.

    In this second approach you need to tell the compiler what types to instantiate the template on.



    You will also need to remeve the misplaced const keyword from your example (in the .cpp file).

IMN logo majestic logo threadwatch logo seochat tools logo