Search code examples
c++templates

Defining methods of several classes in one function using templates


Suppose we have two classes

class A {
   A Method();
}

class B {
   B Method();
}

Method function does some repetitive work, for the example, let's suppose it just returns class's copy.

How can I define this 2 function in 1 using templates? Is it possible?

I've tried to do something like

template <class C>
C C::Method() {
    return *this;
}

Clang gives me error: Nested name specifier 'N::' for declaration does not refer into a class, class template or class template partial specialization


Solution

  • You can't define multiple unrelated functions with syntax like that, but you can add a member to a class by inheriting from a template class.

    template <class T>
    class Cloneable
    {
        T Method() { return *static_cast<T*>(this); }
    }
    
    class A : public Cloneable<A> {}
    
    class B : public Cloneable<B> {}
    

    If you have C++23, you can even drop the cast with an explicit object parameter

    class Cloneable
    {
        template <class T>
        T Method(this T self) { return self; }
    }
    
    class A : public Cloneable {}
    
    class B : public Cloneable {}