c++ - 模板化成员函数 typedef 无法编译

标签 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;
}

在上面的代码中,我尝试使用另一个类中的函数指针 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"

最佳答案

名字Test<A>::Func是从属名称,需要以 typename 为前缀

typename Test< A >::Func f,  

有关更详细的解释,您应该查看以下答案中的 Johannes 解释

关于c++ - 模板化成员函数 typedef 无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4317105/

相关文章:

c - 从 C 函数返回链表结构

c++ - 连接到正在运行的 IE 实例 C++

c++ - 调用库时崩溃

c++ - 模板转换运算符

c++ - ToString<T> 好的做法?

templates - Aurelia:嵌套模板替换

c - 用于定义的 typedef 结构

c++ - 如何强制 C++ 编译器使用寄存器?

c++ - 理解指向设置为 NULL 的对象的指针的问题

c++ - 将模板类拆分为头文件和实现文件时使用类型别名