代码之家  ›  专栏  ›  技术社区  ›  Makogan

在以函数为参数的模板函数中提取输入参数的类型

  •  2
  • Makogan  · 技术社区  · 5 年前

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

    需要这样称呼:

    DoStuff<MyStruct, Fun>(s);

    DoStuff<Fun>(s);

    但是,我不知道如何在模板中指定类型t需要从函数F的签名中推导出来。

    这可能吗?

    1 回复  |  直到 5 年前
        1
  •  4
  •   cigien Jorge Eldis    5 年前

    可以编写一个助手来推断返回的函数指针的参数类型 int

    template<typename T>
    T arg_type(int(*)(T&));
    

    然后稍微重写函数模板,将函数指针作为非类型模板参数,并从中找出参数类型

    template<auto F, typename T = decltype(arg_type(F))>
    void DoStuff(T& s) {
     // ...
    }