Sco*_*ott 4 c++ templates typedef
#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;
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我试图使用另一个类的函数指针typedef.如图所示,它不会编译,但是其他两行中的任何一行都没有注释而不是Test< A >::Func f,行,它编译得很好!这是我在C++中无法做到的事情吗?需要什么语法?
使用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"
Run Code Online (Sandbox Code Playgroud)
名称Test<A>::Func是从属名称,需要加上前缀typename
typename Test< A >::Func f,
Run Code Online (Sandbox Code Playgroud)
有关更详细的说明,请查看以下答案中的约翰内斯解释