CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jul 2009
    Posts
    2

    C++ template question

    Hello all, I am new to using templates and run into a problem:

    I have a file foo.h:

    #ifndef FOO_H_
    #define FOO_H_

    class foo{
    public:
    foo();
    template <unsigned int ID>
    int doSomething();
    virtual ~foo();
    };

    #endif /* FOO_H_ */

    and a foo.cpp:

    #include "foo.h"

    foo::foo() {
    }

    template <unsigned int ID>
    int foo:oSomething(){
    ....
    }

    foo::~foo() {
    }

    and in my main.cpp I want to do something like:

    #include "foo.h"

    int main(int argc, char *argv[]){
    foo *bar = new foo();
    foo->doSomething<2u>();
    return 0;
    }

    The problem is that whenever i try this i get undefined reference to `int foo:oSomething<2u>()

    I have tried a number of variations to call the template (and tbh I am not even sure what I want to is possible) but no success.

    Any Help would be greatly appreciated. Thank you.

  2. #2
    Join Date
    Jul 2009
    Posts
    2

    Re: C++ template question

    I meant to write:

    #include "foo.h"

    int main(int argc, char *argv[]){
    foo *bar = new foo();
    bar->doSomething<2u>();
    return 0;
    }

    typo and problem still exists.

  3. #3
    Join Date
    Nov 2006
    Posts
    1,611

    Re: C++ template question

    The simplest solution is to move the function body dosomething into the header file so the compiler sees it when it instantiates the code for the template.

    ...that applies to all functions of the template class.
    If my post was interesting or helpful, perhaps you would consider clicking the 'rate this post' to let me know (middle icon of the group in the upper right of the post).

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured