gpt4 book ai didi

c++ - 将函数名称作为字符串包装在类中的 std::function

转载 作者:行者123 更新时间:2023-11-28 04:13:35 25 4
gpt4 key购买 nike

我正在尝试包装 std::function在一个类中添加了一个可读的 string函数名称的 std::function .

我确实想出了这个简单的类(在 header.hpp 中定义)

template <typename... Args>
class CExtended_Function
{
public:
explicit CExtended_Function(
const std::function<void(Args...)>& func_type, const std::string& func_name)
: func(func_type)
, function_name(func_name)
{
}

/// Function
const std::function<void(Args...)> func;

/// Function Name
const std::string function_name;
};

我自己的 make 函数如下所示。想法是将函数名称作为模板参数传递给 make 函数。并且 make 函数应该创建一个 std::function实例和一个 std::string实例。

(在 header.hpp 中定义)

template <typename Func_T, typename... Args>
CExtended_Function<Args...> Make_Extended_Function()
{
std::function<void(Args...)> func(Func_T);
std::string func_name(NCommonFunctions::type_name<Func_T>());
CExtended_Function<Args...> res(func, func_name);

return res;
}

哪里type_name<My_Function>()将函数名称返回为 std::string_view

在 header.hpp 中定义

template <class T>
constexpr std::string_view type_name();

但是当像这样使用我的 make 函数时

在source.cpp中使用

static void Test_Callback();

auto test = Make_Extended_Function<Test_Callback>();

我收到错误:

Symbol 'Make_Extended_Function' could not be resolved

您能告诉我为什么会出现此错误吗?

最佳答案

您可能需要在代码中更改一些内容:

  1. Test_Callback 是一个函数,您只能将函数指针作为非类型模板参数传递。 IE。应该是auto test = Make_Extended_Function<&Test_Callback>();相反;
  2. 如果你传递一个函数指针作为模板参数,语法是template<function+pointer_type function pointer> (类似于模板),所以 make_extended_function 应该是 template <auto Func_T, typename... Args>
    CExtended_Function<Args...> Make_Extended_Function()
    相反(我在这里使用“自动”使事情变得更容易)。 type_name() 也是如此

示例代码:

#include <iostream>
#include <functional>
#include <string_view>

using namespace std;
namespace NCommonFunctions {
template <auto T>
std::string type_name() { return "a_name"; }
}
template <typename... Args>
class CExtended_Function
{
public:
explicit CExtended_Function(
const std::function<void(Args...)>& func_type, const std::string& func_name)
: func(func_type)
, function_name(func_name)
{
}

/// Function
const std::function<void(Args...)> func;

/// Function Name
const std::string function_name;
};

template <auto Func_T, typename... Args>
CExtended_Function<Args...> Make_Extended_Function()
{
std::function<void(Args...)> func(Func_T);
std::string func_name(NCommonFunctions::type_name<Func_T>());
CExtended_Function<Args...> res(func, func_name);

return res;
}
void Test_Callback() { cout << "test" << endl; }
int main () {
auto test = Make_Extended_Function<&Test_Callback>();
test.func();
}

关于c++ - 将函数名称作为字符串包装在类中的 std::function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57133093/

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