【问题标题】:Templated member function typedefs won't compile模板化的成员函数 typedefs 不会编译
【发布时间】:2010-11-30 18:26:04
【问题描述】:
#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&lt; A &gt;::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"

【问题讨论】:

  • This answer by Johannes 到一个相关问题将解释所有关于typename 和从属名称的知识,然后再解释更多。

标签: c++ templates typedef


【解决方案1】:

名称Test&lt;A&gt;::Func是依赖名称,需要以typename为前缀

typename Test< A >::Func f,  

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多