c++ - 这个 C++ 模板参数推导不正确吗?

标签 c++ templates c++11 lambda boost-regex

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

错误如下:

 /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 你能解释一下参数推导在这里是如何工作的吗?

最佳答案

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) { ... }

关于c++ - 这个 C++ 模板参数推导不正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39844093/

相关文章:

c++ - 为什么标准不允许在模板参数列表中初始化常量依赖类型?

c++ - 不能在派生模板类中使用 struct 吗?

c++ - C++11 中的 CRTP 调度

c++ - 编译器跳过 C++ 中的可变参数模板/函数

c++ - 是否可以继承默认的 IShellFolder 实现?

c++ - 将类接口(interface)转换为类模板

c++ - 写入文本文件,二进制与 ascii

c++ - 临时数组的元素本身不是右值吗?

c++ - 将参数传递给线程函数(模板化)

c++ - 在变量定义之前转到 - 它的值会发生什么?