English 中文(简体)
带有作为模板化类的参数的模板化函数
原标题:templated function with an argument that is a templated class

我意识到有很多类似的问题,但我找不到任何能解决我问题的问题(阅读:我没有真正理解答案,所以我无法将其应用于我的案例)

我有以下功能:

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

现在,如果我有一个<code>映射<;字符串,bool*>;mapping我可以做以下操作:printVariable(mapping.begin())

这是有效的,现在我也有一个<code>映射<;字符串,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 

我想我可以通过重载函数很容易地解决这个问题。但我想知道为什么上述方法不起作用。

第2版:删除了声称正确解决方案是错误的文本

最佳回答

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

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

但是,请注意,这不是一个可推导的上下文,所以这种形式不是很方便。

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

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

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


这里有一个简单的思维实验,解释为什么在第一种情况下没有可推导的上下文:在下面的<code>foo</code>调用中,应该如何推导<code>t</code〕?

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?
问题回答

暂无回答




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签