I am trying to understand the syntax of a separate compilation of the template function of a member of a non-template class. I work in Microsoft Visual Studio 2013.

Here is my * .h file in which there is a template member function SetBuffer

 #pragma once class Message { public: Message(); ~Message(); public: template <typename TBuffer> void SetBuffer(const TBuffer& buffer); private: std::string buffer_; }; 

The following is the * .cpp file

 #include "pch.h" #include "Message.h" Message::Message() { } Message::~Message() { } template <typename TBuffer> void Message<TBuffer>::SetBuffer(const TBuffer& buffer) { buffer; } 

When compiling, I get these errors:

  Error 1 error C2143: syntax error : missing ';' before '<' D:\programming\c++\pp_samples\modules\_template\class_template\src\Message.cpp 10 1 class_template Error 2 error C2182: 'Message' : illegal use of type 'void' D:\programming\c++\pp_samples\modules\_template\class_template\src\Message.cpp 10 1 class_template Error 3 error C2988: unrecognizable template declaration/definition D:\programming\c++\pp_samples\modules\_template\class_template\src\Message.cpp 10 1 class_template Error 4 error C2059: syntax error : '<' D:\programming\c++\pp_samples\modules\_template\class_template\src\Message.cpp 10 1 class_template Error 5 error C2039: 'SetBuffer' : is not a member of '`global namespace'' D:\programming\c++\pp_samples\modules\_template\class_template\src\Message.cpp 10 1 class_template 

The compiler does not seem to like the definition or the SetBuffer template function of a SetBuffer member. What is the correct syntax for the template function of a member of a non-template class when compiled separately ?? Thank!!

  • The Message class is not a template. Therefore, this Message <TBuffer> :: SetBuffer expression is incorrect. And put the function definition in the header file where the class itself is defined. - Vlad from Moscow

1 answer 1

The Message class itself is not template. And so this qualified name

 Message<TBuffer>::SetBuffer 

incorrect.

And put the function definition in the header file where the class is defined. For example,

 #include <iostream> class Message { public: Message(); ~Message(); public: template <typename TBuffer> void SetBuffer(const TBuffer& buffer); private: std::string buffer_; }; template <typename TBuffer> void Message::SetBuffer(const TBuffer& buffer) { buffer; } int main() { return 0; } 
  • SetBuffer to define the SetBuffer function in a * .cpp file? - Space Rabbit
  • one
    @SpaceRabbit Each compilation unit must include a function definition in order to derive an instance of a non-template function from it. Therefore, the definition of a function should be where its declaration is. - Vlad from Moscow
  • understood thanks. - Space Rabbit