【发布时间】:2015-02-10 16:58:22
【问题描述】:
是的,我知道我应该创建一个迭代器,但是我需要快速完成,并且为任何与 VC++ 相关的东西编写一个合适的迭代器是令人沮丧的。 (这也适用于许多其他标准的东西,并且会增加我的工作量。:()
所以我写了一个 for_each() 算法来处理这个问题:
template <typename K, typename AK, typename V, typename AV>
void for_each(CMap<K, AK, V, AV>& container, std::function<void(AK, AV)> body)
{
POSITION pos = container.GetStartPosition();
while (pos != NULL)
{
AK key;
AV value;
// Get key and value
container .GetNextAssoc(pos, key, value);
body(key, value);
}
}
但是显然VC++不能为函数模板推导出AK和AV。这是正常现象还是 VC++ 的另一个限制?
编辑 这是所要求的错误:
1>d:\projects\clean\cv32\cvcustombuttoninfo.cpp(113): error C2784: 'void for_each(CMap<KEY,ARG_KEY,VALUE,ARG_VALUE> &,std::function<void(AK,AV)>)' : could not deduce template argument for 'std::function<void(AK,AV)>' from 'CCVCustomRibbonInfo::WriteFile::<lambda_0513c2955d2b7b0197efcf2b0ce9322b>'
1> d:\projects\clean\cv32\cvcustombuttoninfo.cpp(66) : see declaration of 'for_each'
这似乎也发生在带有 -std=c++11 参数的 gcc 4.9.0 上。
#include <functional>
template <typename T>
void fn(T t, std::function<void(T)>)
{
}
int main()
{
int i;
fn(i, [](int i){});
return 0;
}
还有 g++ 错误:
/tmp/gcc-explorer-compiler115110-34-1cr9oud/example.cpp: In function 'int main()':
11 : error: no matching function for call to 'fn(int&, main()::)'
fn(i, [](int i){});
^
11 : note: candidate is:
4 : note: template void fn(T, std::function)
void fn(T t, std::function<void(T)>)
^
4 : note: template argument deduction/substitution failed:
11 : note: 'main()::' is not derived from 'std::function'
fn(i, [](int i){});
^
Compilation failed
【问题讨论】:
-
这很奇怪。你怎么称呼它?另外,请添加编译器错误。
-
有趣,如果我用另一个模板参数
T替换std::function<void(AK, AV)>规范,它会编译。