1
votes

I am trying to get a simple example to work for a project (object description), and i would like to avoid some extra coding as shown beside , so my code here :

// My function template foo : i call foo on all my object i want to describe ...
template<class T, class = void>
void foo(T &r);

// I tried this but i the compiler never use this function ...
template<class T, typename std::enable_if<std::is_base_of<Base,   T>::value>::type>
void foo(T &r)
{
    std::cout << "Base or Derivated" << std::endl;
}

template<> void foo<int, void>(int &r)
{
    std::cout << "int" << std::endl;
}

template<> void foo<double, void>(double &r)
{
    std::cout << "double" << std::endl;
}

template<> void foo<Base, void>(Base &r)
{
    std::cout << "Base" << std::endl;
}
// in other librairies we can found other specialization 
template<> void foo<OtherClass, void>(OtherClass &r)
{
    std::cout << "OtherClass" << std::endl;
}

and the main :

int main()
{
    int a(1);
    double b(5.5);
    Base c;
    Derivated d;
    foo(a); // OK 
    foo(b); // OK
    foo(c); // OK
    foo<Base>(d); // OK
    foo(d);  // Compile but erreor at linking 
    return 0;
}

So in fact I have a lot of derivated class from Base ... and I don't want to create all specialization, plus other constraints (library dependencies etc ..). I would like to know if there is a way to call :

foo(d); // decltype(d) = Derivated : public Base

instead of :

foo<Base>(d); // decltype(d) = Derivated : public Base

Thank you for your help

1
Is there any reason you don't pass a reference to the base class as a parameter? Something like this: Base &d = Derivated(); and then foo(d); - mcrlc
I could but i don't see any difference between doing this : foo<Base>(d); and Base &d = Derivated(); foo(d); in termes of complexity ~ usability - Hicham d'Azimani

1 Answers

0
votes

I finally found a " clean way to do what i wanted here my code :

template <class T >
typename std::enable_if<std::is_base_of<Base, T>::value, void>::type
foo(T &r)
{
    std::cout << "T is base of Base" << std::endl;
}

template <class T >
typename std::enable_if<!std::is_base_of<Base, T>::value, void>::type
foo(T &r);


template<> void foo(int &r)
{
    std::cout << "int" << std::endl;
}

template<> void foo(double &r)
{
    std::cout << "double" << std::endl;
}

template<> void foo(OtherClass &r)
{
    std::cout << "OtherClass" << std::endl;
}

int main()
{
    int a(1);
    double b(5.5);
    float f(3.3);
    Base c;
    Derivated d;
    OtherClass e;
    foo(a); // OK foo(int) available
    foo(b); // OK foo(double) available
    foo(c); // OK foo(Base) available
    foo(d); // OK foo(Derivated share the same defenition as foo(Base)
    foo(e); // OK foo Other class available
    foo(f); // OK at compiling but error a linking -> no specialization for        foo(float) available
}