【问题标题】:Deduced template type does not work with `std::function`推导的模板类型不适用于`std::function`
【发布时间】:2020-08-24 06:10:20
【问题描述】:

我试图通过以下段落了解编译错误的根本原因。
我的目标是在更新新设置值时通知每个设置的消费者。
以下是模拟设置 1、2 更新时的简化版本


template <typename T>
struct Setting {
  T Get() {
    return T {};
  }
};

template <typename T>
void ConsumeSettingValue(Setting<T>& a, std::function<void(T)> consumer) {
  consumer(a.Get());
}

int main() {
  Setting<std::string> s1;
  Setting<int32_t> s2;

  ConsumeSettingValue(s1, [](std::string v){
    // Do consume
  });

  ConsumeSettingValue(s2, [](int32_t v){
    // Do consume
  });
}

我正在使用 C++ 17、clang-7、g++8 (devtoolset 8) 和 CentOS 7

这是来自我的编译器的抱怨(clang-7、g++-8 发出完全相同的错误消息,所以我跳过了)

[ 25%] Building CXX object CMakeFiles/UntitledLink.dir/main.cpp.o
/home/kdy/practice/untitled/main.cpp:196:3: error: no matching function for call to 'ConsumeSettingValue'
  ConsumeSettingValue(s1, [](std::string v){
  ^~~~~~~~~~~~~~~~~~~
/home/kdy/practice/untitled/main.cpp:188:6: note: candidate template ignored: could not match 'function<void (type-parameter-0-0)>' against '(lambda at /home/kdy/practice/untitled/main.cpp:196:27)'
void ConsumeSettingValue(Setting<T>& a, std::function<void(T)> consumer) {
     ^
/home/kdy/practice/untitled/main.cpp:200:3: error: no matching function for call to 'ConsumeSettingValue'
  ConsumeSettingValue(s2, [](int32_t v){
  ^~~~~~~~~~~~~~~~~~~
/home/kdy/practice/untitled/main.cpp:188:6: note: candidate template ignored: could not match 'function<void (type-parameter-0-0)>' against '(lambda at /home/kdy/practice/untitled/main.cpp:200:27)'
void ConsumeSettingValue(Setting<T>& a, std::function<void(T)> consumer) {
     ^

在 ConsumeSettingValue、ConsumeSettingValue&lt;std::string&gt;ConsumeSettingValue&lt;int32_t&gt; 之后添加显式类型后,它工作正常
但我认为这些 lambdas 仍然可以推断为 std::function&lt;void(T)&gt;,没有任何特定类型。

请对此有所了解。 我的理论有什么问题? 提前致谢。

【问题讨论】:

    标签: templates lambda c++17


    【解决方案1】:

    找到类似案例:How to convert a lambda to an std::function using templates

    问题是模板不考虑类型之间的转换。 因此std::function 和给定的 lambdas 可以转换,但不一定可以模板推导。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多