为什么编译器无法推断模板参数?

时间:2015-06-29 14:58:34

标签: c++ templates c++11 lambda operator-overloading

我尝试基于C ++ > ggmap(Precip_map, extent = "device") + geom_density2d(data = df, + aes(x = Longitude, y = Latitude), size = 0.3) + stat_density2d(data = df, + aes(x = Longitude, y = Latitude, fill = ..level.., alpha = ..level..), size = 0.01, + bins = 16, geom = "polygon") + scale_fill_gradient(low = "green", high = "red", + guide = FALSE) + scale_alpha(range = c(0, 0.3), guide = FALSE) Error in if (any(h <= 0)) stop("bandwidths must be strictly positive") : missing value where TRUE/FALSE needed Error in if (any(h <= 0)) stop("bandwidths must be strictly positive") : missing value where TRUE/FALSE needed In addition: Warning message: In loop_apply(n, do.ply) : Removed 1106 rows containing non-finite values (stat_density2d). Warning message: In loop_apply(n, do.ply) : Removed 1106 rows containing non-finite values (stat_density2d). 实现一个map运算符。 此运算符的目的是优雅地映射/转换零终止的operator ->*字符串和char*字符串。

wchar_t*

所需的输出是:

template<typename T>
T* operator->*(T* iteratee, std::function<T(T)> mapFun)  {
    for(T* it = iteratee; *it; ++it)
      *it = mapFun(*it);
    return iteratee;
}

using namespace std;

int main()
{
   char msg[] = "Hello World!";

   cout << msg << endl;
   cout << msg->*([](char c ) { return c+1; }) << endl;   
}

但我只得到以下错误:

Hello World!
Ifmmp!Xpsme"

为什么会这样?

我知道,我可以通过明确调用运算符来解决问题,这会使运算符非常不方便

21:15: error: no match for 'operator->*' (operand types are 'char*' and 'main()::<lambda(char)>')
21:15: note: candidate is:
10:4: note: template<class T> T* operator->*(T*, std::function<T(T)>)
10:4: note:   template argument deduction/substitution failed:
21:46: note:   'main()::<lambda(char)>' is not derived from 'std::function<T(T)>'

或向运营商添加第二个模板参数:

cout << operator->*<char>(msg, [](char c ) { return c+1; }) << endl;

但这不是最优的,因为编译器没有抱怨,当我传递一个错误类型的函数时,如下面的用法,编译时没有警告:

template<typename T, typename F>
T* operator->*(T* iteratee, F mapFun)  {
for(T* it = iteratee; *it; ++it)
      *it = mapFun(*it);
    return iteratee;
}

那么,如何在不明确提及模板参数的情况下使用运算符的cout << msg->*([](int i) { return 'a'+i; }) << endl; 版本?

0 个答案:

没有答案