0

I have this template function and class in mc.h/mc.cpp files:

template <class MemT>
class MC;

template <class MemT>
MemT & getMCObj(int t_instNum);

class HBM;

template <class MemT>
class MC
{
public:
    MC(){}

    friend MemT & getMCObj<MemT>(int t_instNum);

private:
    MemT memTobjList[12];
};

class HBM
{
public:
    bool someFunc();

private:
    int num_inst;
};

In the cpp file I have

template<class MemT>
MemT & getMCObj(int t_instNum)
{
    return MC<MemT>::memTobjList[t_instNum];
}

bool HBM::someFunc()
{
    num_inst = 1;
}

template class MC<HBM>;
template HBM & getMCObj<HBM>(int t_instNum);

In main:

int main()
{
    MC<HBM> mC;


    HBM & ptr = getMCObj<HBM>(3);
    ptr.someFunc();

    return 0;
}

I get this error when I compile:

In file included from mc.cpp:1:0:
mc.cpp: In instantiation of 'MemT& getMCObj(int) [with MemT = HBM]':
mc.cpp:16:43:   required from here
mc.h:18:24: error: invalid use of non-static data member 'MC<HBM>::memTobjList'

The first issue was that the I had not explicitly instantiated the template object. I fixed that by adding that to the cpp file. But now there is an error, when I use a friend function getMCObj to access class data member memTobjList. Please help me understand what the issue is here.

Thanks.

rishi_v
  • 1
  • 2
  • 2
    Does this answer your question? [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Mat Apr 22 '20 at 07:38
  • It did help partially. But there's still an error when using the template friend function. – rishi_v Apr 22 '20 at 16:14
  • `MC::memTobjList` is not static, it's a normal member. You need an instance of `MC` to access it – Mat Apr 22 '20 at 16:26
  • Ok. Its working now. Thanks for helping out. – rishi_v Apr 22 '20 at 17:16

0 Answers0