Вопрос

I have template class with inner class

template<class param>
class Nested {
    param obj;
public:
    template<class X>
    class Inner {
        X obj;
    public:
        Inner(X obj) : obj(obj) {}
        X getObj() { return obj; }
    };
    Nested();
    Nested(param obj) : obj(obj) {}
    param getObj() { return obj; }
    virtual ~Nested();
};

I try:

Nested<int>::Inner<int> inner(43);

but i get compilation error:

C++/TemplateClass/Debug/../src/TemplateClass.cpp:20: undefined reference to `Nested<int>::~Nested()'
C++/TemplateClass/Debug/../src/TemplateClass.cpp:20: undefined reference to `Nested<int>::~Nested()'

and next posiblities:

    Nested<int>::Inner inner(43);

../src/TemplateClass.cpp: In function ‘int main()’:
../src/TemplateClass.cpp:17:24: error: invalid use of template-name ‘Nested<int>::Inner’ without an argument list
  typename Nested<int>::Inner inner(43);
                        ^
../src/TemplateClass.cpp:17:35: error: invalid type in declaration before ‘(’ token
  typename Nested<int>::Inner inner(43);
                                   ^
../src/TemplateClass.cpp:18:42: error: request for member ‘getObj’ in ‘inner’, which is of non-class type ‘int’
  cout << "Inner param object: " << inner.getObj() << endl;

How can I create Inner class object?

Это было полезно?

Решение

You have to specify a type for the inner class

Nested<int>::Inner<char> inner(43);

and add some code to your destructor

virtual ~Nested() {}

Другие советы

I tried this on http://www.compileonline.com/compile_cpp11_online.php

It works as intended. For this narrow example you don't need to define a destructor for Nested<> because a Nested<> instance is not created.

#include <iostream>

template<class param>
class Nested {
    param obj;
public:
    template<class X>
    class Inner {
        X obj;
    public:
        Inner(X obj) : obj(obj) {}
        X getObj() { return obj; }
    };
    Nested();
    Nested(param obj) : obj(obj) {}
    param getObj() { return obj; }
    virtual ~Nested();
};

int main()
{
    Nested<int>::Inner<int> temp(43);
    std::cout << temp.getObj() << std::endl;
    return 0;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top