【问题标题】:Passing template typedef as argument to a function template将模板 typedef 作为参数传递给函数模板
【发布时间】:2012-08-12 13:47:26
【问题描述】:

我正在尝试将模板 typedef 作为参数传递给函数模板。但是我收到以下错误:

TestTemplates.cpp:11: 错误:'&' 标记之前的预期 unqualified-id

TestTemplates.cpp:11: 错误:'&' 标记之前的预期 unqualified-id

TestTemplates.cpp:11:错误:'&' 标记之前的预期初始化程序

TestTemplates.cpp:25:错误:“func”未在此范围内声明

#include <iostream>
#include <vector>

template<class T>
struct MyVector
{
    typedef std::vector<T> Type;
};

template<class T>
void func( const MyVector<T>::Type& myVec )
{
    for( MyVector<T>::Type::const_iterator p = myVec.begin(); p != myVec.end(); p++)
    {
        std::cout<<*p<<"\t";
    }
}

int main()
{
    MyVector<int>::Type myVec;
    myVec.push_back( 10 );
    myVec.push_back( 20 );

    func( myVec );
}

谁能指出如何解决这个错误。我看过一些帖子,但找不到解决方案。谢谢

【问题讨论】:

标签: c++ templates typedef function-templates


【解决方案1】:

你需要告诉编译器这是一个类型名

void func( const typename MyVector<T>::Type& myVec )

那么你需要显式地帮助编译器推导出函数的类型:

func<int>( myVec );

顺便说一句,这个问题被称为“two stage lookup

【讨论】:

  • 不,这仍然无法解决。 funcmyVec 参数在不可演绎的上下文中。
  • @Xeo 是对的,它在不可推导的上下文中,但是可以通过显式类型规范来完成:ideone.com/ZpRj5
  • 是的,我遇到了更多错误。 “TestTemplates.cpp:13: error: expected ';' before 'p'", "TestTemplates.cpp:13: error: 'p' is not declared in this scope", "TestTemplates.cpp:25: error: no matching函数调用 'func(std::vector >&)'"
  • 哦,是的,谢谢。现在可以了。我从来没有真正使用过 typename。你能给我指一个关于 typename 工作的教程吗?
  • @nurav :我在调用函数时编辑了显式函数类型的答案。
猜你喜欢
  • 1970-01-01
  • 2011-09-14
  • 1970-01-01
  • 2018-09-28
  • 1970-01-01
  • 2015-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多