Search code examples
c++templatesmethodscompiler-errors

C++ template method definition not matched in class


I'm having trouble putting the definition of a template method outside of its class. Consider the following code that comes from a .h file (stripped the non-essential code to understand the issue):

template <typename T> class CStyleAllocator
{
public:
    // Conversion constructor declaration
    template <typename U> CStyleAllocator(const CStyleAllocator<U>&);
};

// Attempted definition
template <typename T, typename U> CStyleAllocator<T>::CStyleAllocator(
    typename const CStyleAllocator<U>&
)
{
}

The Visual C++ 2010 compiler outputs this error:

1>c:\dev\devworkspaces\dev.main\platform\cpp\memory\cstyleallocator.h(67): error C2244: 'CStyleAllocator<T>::{ctor}' : unable to match function definition to an existing declaration
1>          definition
1>          'CStyleAllocator<T>::CStyleAllocator(const CStyleAllocator<U> &)'
1>          existing declarations
1>          'CStyleAllocator<T>::CStyleAllocator(const CStyleAllocator<U> &)'
1>          'CStyleAllocator<T>::CStyleAllocator(void)'

I'm attempting to define a conversion constructor that is dependent on 2 generic types.

Merging the declaration and the definition inside the class works:

template <typename T> class CStyleAllocator
{
public:
    template <typename U> CStyleAllocator(const CStyleAllocator<U>&) { }
};

Are you seeing what I'm doing wrong?


Solution

  • Try it like this:

    template <typename T>
    template<typename U>
    CStyleAllocator<T>::CStyleAllocator(
        const CStyleAllocator<U>&
    )
    {
    }