gpt4 book ai didi

带有函数指针的 C++ 模板回调

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:30:52 25 4
gpt4 key购买 nike

我想知道是否有可能在不抛出错误的情况下实现这样的目标:

#include <iostream>

template<typename T>
T Sum(T _arg, T (*callbackFunction)(T))
{
T result = (*callbackFunction)(_arg);
return result;
}

template<typename T>
T Callback(T _arg)
{
std::cout << "Callback is called" << std::endl;
return _arg;
}

int main()
{
std::cout << Sum(10.2f, Callback);

getchar();
return 0;
}

这是我得到的:

cannot use function template 'T Callback(T)' as a function argument
could not deduce template argument for 'T' from 'float'

最佳答案

你不能将函数模板作为参数传递,你必须传递一个实例化,这是一个例子:

Live On Coliru

#include <iostream>

template<typename T, typename F>
T Sum(T arg, F f)
{
return f(arg);
}

template<typename T>
T Callback(T arg)
{
std::cout << "Callback is called" << std::endl;
return arg;
}

auto Callback2 = [](auto arg)
{
std::cout << "Callback2, a generic lambda, is called" << std::endl;
return arg;
};

int main()
{
std::cout << Sum(10.2f, Callback<float>) << std::endl;
std::cout << Sum(10.2f, Callback2) << std::endl;
std::cout << Sum(10.2f, [](auto arg) {
std::cout << "An in-place generic lambda is called" << std::endl;
return arg;
}) << std::endl;

getchar();
return 0;
}

关于带有函数指针的 C++ 模板回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28784511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com