将模板typedef作为参数传递给功能模板

将模板typedef作为参数传递给功能模板

本文介绍了将模板typedef作为参数传递给功能模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to pass a template typedef as argument to a function template. However I get following errors:

TestTemplates.cpp:11:错误:&"令牌之前的预期unqualified-id

TestTemplates.cpp:11: error: expected unqualified-id before ‘&’ token

TestTemplates.cpp:11:错误:&"令牌之前的预期初始化程序

TestTemplates.cpp:11: error: expected initializer before ‘&’ token

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

TestTemplates.cpp:25: error: ‘func’ was not declared in this scope

#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 );
}

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

Can anyone point out how to fix this error. I have looked at some posts, but cannot find the solution. Thanks

推荐答案

您需要告诉编译器它是类型名

You need to tell the compiler that it's a typename

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

然后,您需要显式地帮助编译器推断函数的类型:

Then you need to explicitly help the compiler deduce the type for the function:

func<int>( myVec );

顺便说一句,该问题称为" 两阶段查找 "

BTW, the issue is called "two stage lookup"

这篇关于将模板typedef作为参数传递给功能模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 08:11