【问题标题】:C++ use function argument type for template argument deductionC++ 使用函数参数类型进行模板参数推导
【发布时间】:2016-05-25 07:49:09
【问题描述】:
template<typename T>
void f(void (*func)(const T&)) {
    (*func)(T());
}

void func(const int& i) {
    std::cout << i << std::endl;
}

int main() {
    f(&func);
}

这里f的模板参数T (= int)是根据函数func的第一个参数自动扣除的。

这也可以扩展为与通用函子(lambda 函数或其他函数对象)一起使用。可能与第二个函数一起使用,即类似的东西

template<typename T, typename Function> void f(Function func);

template<typename Function>
void call_f(Function func) {
    using arg_type = first_argument_type_t<Function>; // ???
    f<arg_type, Function>(func);
}

f 中落入func 应该可以被编译器内联,所以不能使用std::function

【问题讨论】:

  • 推导参数类型需要考虑很多情况。
  • 你不会在一般情况下使用它,即,如果该仿函数是通用 lambda,或者具有重载/模板化的类类型实例 operator()

标签: c++ templates c++11 c++14 functor


【解决方案1】:

我通常使用像this(GPL-3 许可)这样的函数特征代码来做到这一点:

template <typename F>
using first_argument_type_t =
     typename sharemind::FunctionTraits<F>::template argument<0u>::type;

但也有 Boost function_traits 替代方案,它可能会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 1970-01-01
    • 2020-07-09
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多