const在std :: function模板参数中

时间:2016-08-09 14:36:35

标签: c++ templates c++11

为什么在G ++ 5.3.1中无法编译(使用--std = c ++ 1y):

#include <iostream>
#include <vector>
#include <functional>

using std::cout;
using std::endl;

template<typename InputIterator>
void foo(InputIterator i, std::function<bool(typename const std::iterator_traits<InputIterator>::value_type&)> f)
{
    cout << f(*i) << endl;
}

int main() {
    std::vector<int> v { 1,2,3 };
    foo(v.begin(), [] (const int& a) -> bool { return false; } );
}

此操作失败并显示以下消息:

g++ -std=c++1y -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"source.d" -MT"source.o" -o "source.o" "../source.cc"
../source.cc:16:110: error: template argument 1 is invalid
 void foo(InputIterator i, std::function<bool(typename const std::iterator_traits<InputIterator>::value_type&)> f)
                                                                                                              ^
../source.cc:16:110: error: template argument 1 is invalid
../source.cc:16:110: error: template argument 1 is invalid
../source.cc:16:110: error: template argument 1 is invalid
../source.cc:16:110: error: template argument 1 is invalid
../source.cc:16:32: error: ‘std::function’ is not a type
 void foo(InputIterator i, std::function<bool(typename const std::iterator_traits<InputIterator>::value_type&)> f)
                                ^
../source.cc:16:40: error: expected ‘,’ or ‘...’ before ‘<’ token
 void foo(InputIterator i, std::function<bool(typename const std::iterator_traits<InputIterator>::value_type&)> f)
                                        ^
../source.cc: In function ‘int main()’:
../source.cc:23:61: error: no matching function for call to ‘foo(std::vector<int>::iterator, main()::<lambda(const int&)>)’
  foo(v.begin(), [] (const int& a) -> bool { return false; } );
                                                             ^
../source.cc:16:6: note: candidate: template<class InputIterator> void foo(InputIterator, int)
 void foo(InputIterator i, std::function<bool(typename const std::iterator_traits<InputIterator>::value_type&)> f)
      ^
../source.cc:16:6: note:   template argument deduction/substitution failed:
../source.cc:23:61: note:   cannot convert ‘<lambda closure object>main()::<lambda(const int&)>{}’ (type ‘main()::<lambda(const int&)>’) to type ‘int’
  foo(v.begin(), [] (const int& a) -> bool { return false; } );
                                                             ^

(注意由于我省略了一些标题注释,行号被8关闭。

但是,如果我删除所有const限定符,那么它编译得很好。

1 个答案:

答案 0 :(得分:2)

我认为你想要const typename ...而不是typename const ...:)