Search code examples
c++templatestype-parameter

C++ template member function already defined with same type


I have this simple code below, a template with 2 type parameters. If I declare my class with the same type (like BidirectionalMap<int,int>), I receive an error:

int BidirectionalMap<T,S>::operator [](T) const' : member function already defined or declared  

Here's my template code:

template <class T, class S>

class BidirectionalMap{
    int count(T t){
        return 1;
    }
    int count(S s){
        return 1;
    }
};

Solution

  • The error you got is normal, because after substitution you have

    template <>
    class BidirectionalMap<int, int>
    {
        int count(int t){ return 1; }
        int count(int s){ return 1; } // Duplicated method
    };
    

    To solve that, you may provide partial specialization:

    template <class T>
    class BidirectionalMap<T, T>
    {
        int count(T t) { return 1; }
    };
    

    In C++20, you might use requires to "discard" methods:

    template <class T, class S>
    class BidirectionalMap
    {
        int count(T t) requires(!std::is_same<T, S>::value) { /*..*/ }
        int count(S s) requires(!std::is_same<T, S>::value) { /*..*/ }
        int count(T t) requires( std::is_same<T, S>::value) { /*..*/ }
    };