Alex
Alex

Reputation: 5439

Declaring a template function with a template function pointer

First time I use templates and pointer to member functions at the same time and I stumbled across following problem.

I declared a struct Proxy for a typedef, since templates and typedefs are not working together (I know this should be possible in C++11, MSVC++ does not accept it though). Now I want to declare a templated(!) function which uses the proxy with the templates type. This is what causes the error at compilation. Please have a look at the (simplified) code below, I added some examples to clarify the problem.

I am working with standard VC++ 2010 (no CLR/CLI).

template<typename T>
struct Proxy
{
    typedef bool (CClass::*MethodPtr)(const T* const objectX);
}

class CClass
{
    // warning: dependent name is not a type
    // error:: Method can not be a template definition
    template<typename T>
    bool Method( Proxy<T>::MethodPtr );

    // this works, but i want to specify T instead of int of course
    template<typename t>
    bool method( Proxy<int>::MethodPtr );

    // this is what i use
    template<typename T>
    bool Method( bool (CClass::*MethodPtr)(const T* const objectX) );
}

template<typename T>
bool CClass::Method( bool (CClass::*MethodPtr)(const T* const objectX) ) 
{
    // next line compiles without problems
    Proxy<T>::MethodPtr ptr2;
}

Upvotes: 1

Views: 655

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254471

You need to use typename to indicate where a dependent name is a type; in particular, the first declaration of Method should be:

template<typename T>
bool Method( typename Proxy<T>::MethodPtr );

and the line that you say compiles without problems (but only because VC++ has an "extension" that accepts ill-formed code) should be:

// next line compiles without problems
typename Proxy<T>::MethodPtr ptr2;

You're also missing semicolons after the class definitions, and a forward declaration of CClass before the definition of Proxy.

Upvotes: 5

K-ballo
K-ballo

Reputation: 81349

// warning: dependent name is not a type
// error:: Method can not be a template definition
template<typename T>
bool Method( Proxy<T>::MethodPtr );

MethodPtr is dependent on template argument T, you should be using typename.

// next line compiles without problems
Proxy<T>::MethodPtr ptr2;

You should use typename there as well, not sure why it compiles.

Upvotes: 2

Related Questions