开发者

Templated member function typedefs won't compile

#include <iostream>
#include <string>
using namespace std;
开发者_StackOverflow
void printstr( const string & s ) { cout << s << endl; }

template < typename A >
class Test
{
public:
    typedef void (*Func)( const A & );
};

typedef void (*Func)( const string & );

template < typename A >
void bind(
        Test< A >::Func f,           //<---- does NOT compile
        //Func f,                    //<---- compiles & works!
        //void (*f)( const A & ),    //<---- compiles & works!
        const A & a) { f( a ); }


int main( )
{
    bind( printstr, string("test") );
    return 0;
}

In the code above, I am trying to use a function pointer typedef from another class. As shown, it does not compile, but with either of the other two lines uncommented instead of the Test< A >::Func f, line, it compiles fine! Is this something I can't do in C++? What syntax is needed?

Using g++ 4.4.3, I get

test.cpp:20: error: variable or field "bind" declared void
test.cpp:20: error: expected ")" before "f"
test.cpp:23: error: expected primary-expression before "const"


The name Test<A>::Func is a dependent name and needs to be prefixed with typename

typename Test< A >::Func f,  

For a more detailed explanation you should check out Johannes explanation in the following answer

  • Where and why do I have to put the "template" and "typename" keywords?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜