简体   繁体   English

模板化的成员函数typedefs无法编译

[英]Templated member function typedefs won't compile

#include <iostream>
#include <string>
using namespace std;

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. 在上面的代码中,我试图使用另一个类的函数指针typedef。 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! 如图所示,它不会编译,但是用其他两行中的任何一条代替注释Test< A >::Func f,行,它都可以正常编译! Is this something I can't do in C++? 这是我在C ++中做不到的事情吗? What syntax is needed? 需要什么语法?

Using g++ 4.4.3, I get 使用g ++ 4.4.3,我得到

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 名称Test<A>::Func是一个从属名称,需要以typename作为前缀

typename Test< A >::Func f,  

For a more detailed explanation you should check out Johannes explanation in the following answer 有关更详细的说明,请查看以下答案中的约翰内斯说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM