2016-10-04 85 views
0
#include <iostream> 
#include <regex> 
int main(void) 
{ 
    std::cmatch cm; 
    std::regex_match("subject", cm, std::regex("(sub)(.*)")); 
    //std::for_each(cm.begin(), cm.end(), [](const std::sub_match<const char *> &s){ <---- Working statement 

    std::for_each(cm.begin(), cm.end(), [](const std::cmatch &s){ /*<--- Non-working statement*/ 
     std::cout << "match:" << s.str() <<std::endl; 
    }); 
    return 0; 
} 

的錯誤是如下:這是C++模板參數推導不正確?

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:853:9: error: no matching function for call to object of type '(lambda at main.cpp:73:41)' 
__f(*__first); 
^~~ 
main.cpp:73:10: note: in instantiation of function template specialization 'std::__1::for_each<std::__1::__wrap_iter<const std::__1::sub_match<const char *> *>, (lambda at main.cpp:73:41)>' requested here 
std::for_each(cm.begin(), cm.end(), [](const std::match_results<const char*> &s){ 
^ 
main.cpp:73:41: note: candidate function not viable: no known conversion from 'const std::__1::sub_match<const char *>' to 'const std::match_results<const char *>' for 1st argument 
std::for_each(cm.begin(), cm.end(), [](const std::match_results<const char*> &s){ 
^ 
maintool.cpp:73:41: note: conversion candidate of type 'void (*)(const std::match_results<const char *> &)' 
1 error generated. 

在非工作例如爲什麼模板推導出std::__1::for_each<std::__1::__wrap_iter<const std::__1::sub_match<const char *> *>

我期待param將被推斷爲std:::cmatch 你能解釋一下param扣除在這裏是如何工作的嗎?

回答

3

std::cmatchstd::match_results<char const*>的別名;你想要std::sub_match<char const*>,其別名是std::csub_match

std::for_each(cm.begin(), cm.end(), [](const std::csub_match &s) { ... } 
+0

我的問題是爲什麼它的'csub_match'爲什麼不'cmatch'? – PnotNP

+0

@NulledPointer:因爲['std :: match_results :: value_type'是'std :: sub_match '](http://en.cppreference.com/w/cpp/regex/match_results)。這裏沒有什麼特別的'match_results',這就是任何迭代器的工作原理。 – ildjarn

+0

我想我仍然想念迭代器是如何工作的。不好先看看。同時不滿意你的答案 – PnotNP