1

This is my first time ever attempting to use class templates (I'm very new to C++)

I'm trying to create a very simple Number class. To start, I'm creating a ToString method. As of now, for testing purposes, I just want ToString to return the string "testing".

When I run my code, I get the following error:

Undefined symbols for architecture x86_64: "Number<int>::ToString()", referenced from: _main in main.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [build/ml] Error 1

Here is my code, any help is appreciated:

main.cpp

#include "number.h"

int main(int argc, char* argv[]) {
    Number<int> x(15);
    x.ToString();
    return 0;
}

number.h

#ifndef _NUMBER_
#define _NUMBER_

#include <iostream>

template <class T> 
class Number {
    private:
        T m_val;
    public:
        Number(T val) : m_val(val) {};
        std::string ToString();
};

#endif

number.cpp

#include "number.h"

template<class T> 
std::string Number<T>::ToString() {
    return std::string("testing");  
}
David
  • 693
  • 1
  • 7
  • 20
  • Unlike normal code, you have to put templates entirely in the header file. (That's a simplification, but the easiest solution) – Neil Kirk Sep 05 '15 at 02:47
  • Make `ToString` a const function. You don't need to surround the quote with `std::string` – Neil Kirk Sep 05 '15 at 02:48

1 Answers1

1

Try to include number.cpp in main.cpp (as a temporary workaround), instead of include number.h. Or move the function definition of ToString() into number.h, and only use number.h.

See Why can templates only be implemented in the header file?

Community
  • 1
  • 1
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Are you really advising the OP to include a .cpp file in another .cpp file? http://stackoverflow.com/questions/1686204/why-should-i-not-include-cpp-files-and-instead-use-a-header – NathanOliver Sep 05 '15 at 03:04
  • 1
    I ended up just moving the function definition of ToString into number.h – David Sep 05 '15 at 06:35