从 std::any 序列化的通用函数

Generic function to serialize from std::any

我正在尝试创建一个函数来序列化存储为 std::any 的对象。这个想法是,对象与一个可以序列化它的函数一起存储在 std::any 中,然后在对象上调用该函数。

我 运行 遇到以下问题。

#include <iostream>
#include <any>

using namespace std;

template<typename T, int (*F)(T& t)>
int _GetDataFromAny(std::any& input)
{
    return F(std::any_cast<T&>(input));
}

struct MyStruct
{
    int val = 69;  
};

int Fun(MyStruct& str) { return str.val; }

template<typename T>
void DoStuff(T& s, int (*F)(T&))
{
    auto an = make_any<T>(s);
    cout << _GetDataFromAny<MyStruct, F>(an);
}

int main()
{
    MyStruct s = {71};

    DoStuff(s, Fun);     /* does not compile */
    
    /* Works fine */
    auto an = make_any<MyStruct>(s);
    cout << _GetDataFromAny<MyStruct, Fun>(an);

    return 0;
} 

此代码有 2 个版本,一个有 DoStuff 行,一个没有。 DoStuff 背后的想法是它可以构造 std::any 容器和一个适当的函数来序列化该对象,但是我无法编译 DoStuff (但是其他所有东西都可以编译)。

我得到的确切错误是:

main.cpp: In instantiation of ‘void DoStuff(T&, int (*)(T&)) [with T = MyStruct]’:
<span class="error_line" onclick="ide.gotoLine('main.cpp',38)">main.cpp:38:19</span>:   required from here
main.cpp:31:41: error: no matching function for call to ‘_GetDataFromAny(std::any&)’
     cout << _GetDataFromAny<MyStruct, F>(an);
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~
main.cpp:15:5: note: candidate: template int _GetDataFromAny(std::any&)
 int _GetDataFromAny(std::any& input)

我不完全确定模板替换失败的原因。

F 作为函数参数不能用作模板参数。这不是 constant expression.

F 必须是模板参数才能编译此代码。函数参数永远不是常量表达式。