How to declare the type of self-regulatory template?

How to declare a template type that refers to itself?

template <class T = Animal> class Animal
{
public:
    T getChild ();
}

With this, I get a compiler error regarding the missing type specifier. I tried to send-declare Animalwithout success.

I am trying to impose a type restriction. A Lioncan only have Lionas a child, a Bearhas Bear, etc.

EDIT

I will post part of the actual class. This is a template for classes that can appear in a linked list:

template <class T = Linked<T> > class Linked
{
private:
    T* m_prev;
    T* m_next;
}

I want to ensure that a class can only specify an object of one class (or subclass).

+3
source share
4 answers

The usual way to do something like a linked list is:

template <class T> class Linked
{
private:
    Linked<T>* m_prev;
    Linked<T>* m_next;
}

, , , ?

+1

- Animal , " " :

template<class T> class Animal;//you'll need this forward declaration

template <class T = Animal<int> > class Animal //int is just an example
{
public:
    T getPrey ();
}
+4

OP , , , . , , , . . , . , :

template<typename T> int function_template(int);
typedef int function_type(int);
void eats_a_function(function_type&); // needs a reference to function

std::vector< std::vector > vec0; // std::vector is not a type
std::vector< std::list > vec1; // std::list is not a type
eats_a_function(function_template); // function_template is not a function

, vec1 std::list std::vector. ( ) . - .

:

std::vector< std::vector<int> > vec2; // std::vector<int> is a type
std::vector< std::list<double> > vec3; // std::list<double> is a type
eats_a_function(function_template<long>); // function_template<long> is a function

, vec2 , .


- , , :

// expects a template that expects a type
template<template<class> class T> struct indirection {};

// forward decl. for defaulting the parameter
template<typename T> struct recursive;

// template that expects a type
template<typename T = indirection<recursive> > struct recursive {};

, , ( T indirection). , rebind, T.

+4

, . , . , , (, Animal), . . , .

, .

:    Animal   {   :       T getPrey();   }

, :

template <class T=Cheetah> class Animal
{
public:
    T getPrey ();
}

, .

+1
source

All Articles