c++ - 如何从第一个参数推导出第二个参数类型?

标签 c++ c++11 templates lambda c++17

我是模板元编程的新手。第二个参数将与传递的函数参数相同。我想从 Func 推导出第二个参数类型。

template<typename Func>
void execute(Func func, decltype(Func) t) 
{
    std::cout << func(t) << std::endl;
}

int main() 
{
    std::function<int(float)> func1 = [](float f) { return int(f); };
    execute(func1,1.5);
    return 0;
}

这可行,但我不想声明额外的 typenameme T,因为信息已经在 Func 中可用,所以为什么不推断。

template<typename Func, typename T>
void execute(Func func, T t) 
{
    std::cout << func(t) << std::endl;
}

最佳答案

I want to deduce the second parameter type from Func

I don't want to declare additional typename T

除了在 binding with the argument 之后将可调用对象传递给函数外,我没有看到任何满足您要求的简单解决方案。 .

以下将确保您的第二个要求,而不需要对您的原始代码进行太多更改。

#include <functional>
#include <iostream>

template<typename Func>
void execute(Func func) {
    std::cout << func() << std::endl;
}
int main() 
{
    auto func1 = std::bind([](float f) { return int(f); }, 2.5f);
    execute(func1);
    return 0;
}

关于c++ - 如何从第一个参数推导出第二个参数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52231669/

相关文章:

指针数组的 C++ 内存分配

c++ - 如何从函数内部将函数指针传递给函数

c++ - unistd read() 不起作用

c++11 - std::move 构造后对象的状态

c++ - vector 中的不可复制元素

c++ - 编译但每次都崩溃#class template c++

c++ - 我怎样才能用另一个数组切换一个数组的元素?

c++ - 压力-ng : Writing an application program using execv to invoke stress-ng commands and return if it is success or failure

c++ - 使用模板转换特定类型的参数

c++ - 无法编译: error: expected primary-expression before '(' token