Is this c++ template param deduction incorrect?

久未见 提交于 2019-12-25 07:59:52

问题


#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;
}

The error is as following:

 /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.

In non-working example why is template deduced as std::__1::for_each<std::__1::__wrap_iter<const std::__1::sub_match<const char *> *> ?

I was expecting param will be deduced to be std:::cmatch Can you please explain how param deduction is working here?


回答1:


std::cmatch is an alias for std::match_results<char const*>; you want std::sub_match<char const*>, whose alias is std::csub_match.

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


来源:https://stackoverflow.com/questions/39844093/is-this-c-template-param-deduction-incorrect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!