Expected initializer before '<' token

13,256

Solution 1

I finally solved the problem by removing the myClass.cpp from the build configuration. Not sure why this was necessary, but it works perfectly now.

Solution 2

Put the implementation of the method in the header file (.h) too

The compiler needs to know details of implementation in translation unit.

Share:
13,256
Admin
Author by

Admin

Updated on June 16, 2022

Comments

  • Admin
    Admin almost 2 years

    I have a template class myClass prototyped in a header file, and am implementing it in a .cpp file that is included at the end of the header file. When I use the code:

    template<typename T>
    class myClass {
    public:
        void myFunction(const T item);
    };
    

    in the header file and

    template <class T>
    void myClass<T>::myFunction(const T item)
    {
    //stuff
    }
    

    in the implementation file, I get the above error on line 2 of the implementation code. I have used this same exact syntax in another program with successful compilation and correctly functioning results, so I am quite confused. There are three different function definitions in the .cpp file and all have this same error on their respective lines. I assume I am making a small error but I really can't seem to figure it out.

    Help and explanation are very much appreciated.

    EDIT:

    Here is an SSCCE which has the same error: main.cpp

    #include <iostream>
    #include "myClass.h"
    
    using namespace std;
    
    int main(){
    myClass<int> example;
    example.myFunction(1);
    return 0;
    }
    

    myClass.h

    #include<iostream>
    
    #ifndef MYCLASS_H_
    #define MYCLASS_H_
    
    template<typename T>
    class myClass {
    public:
        void myFunction(const T item);
    };
    
    #include "myClass.cpp"
    #endif /* MYCLASS_H_ */
    

    myClass.cpp

    using namespace std;
    
    template <class T>
    void myClass<T>::myFunction(const T item)
    {
        cout << "Hello World!";
    }
    

    and I am using Code::Blocks 10.05 with the GNU GCC compiler.