我意识到有很多类似的问题,但找不到解决我的问题的方法(请阅读:我并没有真正理解答案,因此无法将其应用于我的案例)

我有以下功能:

void printVariable(map<string, bool*>::iterator it)
{
   cout << it->first << " " << *(it->second) << endl;
}


现在,如果我有map<string, bool*> mapping,则可以执行以下操作:printVariable(mapping.begin());

可行,现在我也有一个map<string, int*>并希望能够执行相同的操作,因此我确定我更改了printVariable函数:

template <typename T>
void printVariable(map<string, T*>::iterator it)
{
   cout << it->first << " " << *(it->second) << endl;
}


但是,这会产生编译错误(gcc):

error: variable or field 'printVariable' declared void
error: expected ')' before 'it'


我想我可以通过重载该功能来解决此问题。但是我想知道为什么上面的方法不起作用。

Edit2:删除了声称正确解决方案的文本错误

最佳答案

您必须说typename来消除从属名称的歧义:

template <typename T>
void printVariable(typename map<string, T*>::iterator it)
//                 ^^^^^^^^


但是,请注意,这不是可推论的上下文,因此这种形式并不是十分方便。

更好的是,只需将整个迭代器作为模板参数即可:

template <typename Iter>
void printVariable(Iter it)
{ /* ... */ }


这样,您还可以捕获具有非标准比较器或分配器的映射以及无序映射等。



这是一个简单的思想实验,用于说明为什么在第一种情况下您没有可推论的上下文:如何在随后的T调用中推论foo

template <typename T> void foo(typename Bar<T>::type);

template <typename T> struct Bar { typedef char type; };
template <> struct Bar<int>      { typedef int type; };
template <> struct Bar<double>   { typedef int type; };

foo(10); // What is T?

关于c++ - 具有作为模板类的参数的模板函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10140727/

10-14 20:52
查看更多