c++ - 从函数参数推断模板类型

标签 c++ templates c++17 type-inference

我不确定问题的标题,但基本上我很好奇如何创建一个类似访问者的函数,该函数可以对正确使用类型推断的集合上的某些类型进行操作。

例如,集合包含从单个基类 (Base) 继承的对象。一些操作仅适用于特定的子类(例如,FooBar 继承自 Base)。

一个实现可以是

template<class T, class F>
void visit(F f)
{
  for (auto c : the_collection) {
    if (auto t = dynamic_cast<T*>(c)) {
      f(t);
    }
  }
}

这里的问题是调用这样的函数需要指定类类型 FooBar两次:

visit<FooBar>([](FooBar* f) { f->some_method(); });

我想使用类型推断,所以我可以写 visit([](FooBar* f) ... , 但无法设法获得正确的模板。

例如:

template<class T>
using Visitor = std::function<void(T*)>;
template<class T>
void visit(const Visitor<T>& f)
{
  for (auto c : the_collection)
    if (auto t = dynamic_cast<T*>(c))
      f(t);
}

visit<FooBar>([](FooBar*) ... 一起工作但不是 visit([](FooBar*) ... .

no matching overloaded function found

void visit(const std::function<void(T *)> &)': could not deduce template argument for 'const std::function<void(T *)> &' from '{....}::<lambda_2c65d4ec74cfd95c8691dac5ede9644d>

是否可以定义一个模板以这种方式推断类型,或者语言规范不允许这样做?

最佳答案

您标记了 C++17,因此您可以使用 std::function 的推导指南。

那么下面的事情呢?

template <typename>
struct first_arg_type;

template <typename R, typename T0, typename ... Ts>
struct first_arg_type<std::function<R(T0, Ts...)>>
 { using type = T0; };

template <typename F>
void visit (F const & f)
 {
   using T = typename first_arg_type<decltype(std::function{f})>::type;

   for (auto c : the_collection)
      if (auto t = dynamic_cast<T>(c))
         f(t);
 }

请注意,您可以在 std::function 中使用标准类型 first_argument_type 而不是自定义类型特征 first_arg_type,所以

   using T = typename decltype(std::function{f})::first_argument_type;

不幸的是,std::function::first_argument_type 从 C++17 开始被弃用,并将从 C++20 中删除。

关于c++ - 从函数参数推断模板类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55810126/

相关文章:

c++ - Qt4 应用程序中 "fork()"的可移植方式?

c++ - 使用 target_link_libraries 时避免自动添加 "lib"前缀

c++ - QT 图形场景/ View - 用鼠标四处移动

c++ - 使用非专用模板化类型作为模板参数

python - Jinja2 和 Flask : Pass variable into parent template without passing it into children

c++ - C++11、14、17 或 20 是否为 pi 引入了标准常量?

c++ - 我不能使用运算符 ""sv 作为 fstream() 的参数吗?

c++ - 从类定义中推导模板参数类型

c++ - Curl 7.43.0 不会在 MSVC 2013 中构建

c++ - 选择成员函数而不是成员函数定义中具有相同名称的函数