African_king
African_king

Reputation: 187

How to use a type defined and associated with a Template parameter in a class Template?

Below is an implementation of the above question.

#include <iostream>
#include <map>

class Data {
    int val;
};

template<class T>
class Test {
public:
    Test(){};
private:
    typename T::container  _data;
};

class FunTest:public Test<FunTest> {
public:
    typedef std::map<uint16_t, FunTest > container;
    FunTest():Test(){}
};


int main()
{
    FunTest object;
    std::cout << "Hello World!\n";
}

I tried the above but I get the error

Error   C2039   'container': is not a member of 'FunTest'   Temp    

Any insight on why this gives an error is much appreciated.

Upvotes: 1

Views: 79

Answers (1)

fbi open_up
fbi open_up

Reputation: 101

According to user17732522

Test will instantiate the template specialization before container is declared, so T::container cannot use it.

So I guess one solution could be to move the typedef to Test class as a protected variable.

#include <iostream>
#include <map>

template<class T>
class Test {
public:
    Test() {};

protected:
    typedef std::map<uint16_t, T> container;

private:
    typename container  _data;
};

class FunTest :public Test<FunTest> {
public:
    
    FunTest() :Test() {}
    //Test<FunTest>::container c; access here as well if needed
};


int main()
{
    FunTest object;
    std::cout << "Hello World!\n";
} 

Upvotes: 1

Related Questions