TigerCoding
TigerCoding

Reputation: 8720

C++ template definition results in unknown type name

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?

Upvotes: 1

Views: 7782

Answers (4)

Zac Howland
Zac Howland

Reputation: 15872

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);
}

Upvotes: 1

sehe
sehe

Reputation: 392903

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?

Upvotes: 3

Avt
Avt

Reputation: 17043

You should add

template <class valueType>

also before method implementation and change

void MyClass:: ...

to

void MyClass<valueType>:: ...

Upvotes: 1

Daniel
Daniel

Reputation: 31569

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);
}

Upvotes: 1

Related Questions