1

I'm learning about templates in C++. In MyClass.h:

template <class valueType>
void valueToMap(const std::string key, const valueType value);

In MyClass.cpp:

void MyClass::valueToMap(const std::string key, const valueType value) // error
                                                      ^
{
    _map[key] = std::to_string(value);
}

The error is: Unknown type name 'valueType' I've included the header file, so what am I doing wrong?

TigerCoding
  • 8,710
  • 10
  • 47
  • 72

4 Answers4

3

It needs to be a template nonetheless

template <typename valueType>
void MyClass<valueType>::valueToMap(const std::string key, const valueType value) // error
                                                      ^
{
    _map[key] = std::to_string(value);
}

However Keep in mind:

Why can templates only be implemented in the header file?

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633
1

You need to repeat the template during both in declaration and in definition:

template <class valueType>
void MyClass::valueToMap(const std::string key, const valueType value)
{
    _map[key] = std::to_string(value);
}
Daniel
  • 30,896
  • 18
  • 85
  • 139
1

You should add

template <class valueType>

also before method implementation and change

void MyClass:: ...

to

void MyClass<valueType>:: ...
Avt
  • 16,927
  • 4
  • 52
  • 72
1

When dealing with templates, you cannot separate the class declaration and class implementation into separate files (at least not without including the .cpp file at the end of the .h file). This is due to how templates are compiled.

The simplest ways to do what you are trying to do is to either inline your functions:

template <class valueType> // assuming this is also at the class level
void valueToMap(const std::string key, const valueType value)
{
    _map[key] = std::to_string(value);
}

Or place the implementation after the class declaration in the header file:

template<class valueType>
class MyClass
{
public:
    void valueToMap(const std::string key, const valueType value);
};

template<class valueType>
void MyClass<valueType>::valueToMap(const std::string key, const valueType value)
{
    _map[key] = std::to_string(value);
}
Zac Howland
  • 15,777
  • 1
  • 26
  • 42