gpt4 book ai didi

c++ - 将模板 typedef 作为参数传递给函数模板

转载 作者:行者123 更新时间:2023-11-30 03:00:31 24 4
gpt4 key购买 nike

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

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

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

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

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

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

最佳答案

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

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

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

func<int>( myVec );

顺便说一句,这个问题叫做“ two stage lookup

关于c++ - 将模板 typedef 作为参数传递给函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11922657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com