Creating a virtual member function with a return type template

I have a base class (with which I want to simulate interfaces)

template<typename TType>
class Base
{
public:
    virtual SomeTemplatedClass<TType> GetTheObject() = 0;
}

and obviously a derived class

template<typename TType>
class Derived : public Base<TType>
{
public:
    virtual SomeTemplatedClass<TType> GetTheObject() = 0;
}

but for a specific type I intend to specialize "GetTheObject"

template<> 
SomeTemplatedClass<int> Derived<int>::GetTheObject()
{
    return 5;
}

Visual Studio 2015 complains that it cannot instantiate an abstract class when I try to use

Derived<int>

Providing even throwing behavior for the template version

class Derived : public Base<TType>
{
public:
    virtual SomeTemplatedClass<TType> GetTheObject() override
    {
        throw <something>;
    }
}

Let everything compile. So my question is: Why do I need to provide general behavior when I have a specific and unique one that you need?

+4
source share
1 answer

GetTheObject, . .

template<typename TType>
class Derived : public Base<TType>
{
public:
     virtual SomeTemplatedClass<TType> GetTheObject();
}

.

( ).

, .

class A { virtual void f() = 0; }; // A is abstract
void A::f() {} // A is still abstract

.

template <int> class A { virtual void f() = 0; }; // A is abstract
template <int k> void A<k>::f() {} // A is still abstract

.

template <int> class A { virtual void f() = 0; }; // A is abstract
template <int k> void A<k>::f() {} // A is still abstract
template <> void A<42>::f() {} // srsly are you kidding?

, , - , , .

+3

Source: https://habr.com/ru/post/1691094/


All Articles