Template:通过函数原型确定模板参数

Template: Determine template arguments by function prototype

本文关键字:参数 原型 函数 Template      更新时间:2023-10-16

我有函数指针类型或函数原型:

int function (int arg);
typedef int (*function_t) (int arg);

和类似的模板类

template <typename T_ret, typename... T_args> 
class caller {
    T_ret (*m_p) (T_args... args);
public:
    T_ret call (T_args... args) {
        return m_p(args);
    }
    caller (T_ret (*p)(T_args...args)) : m_p(p) {}
};

是否可以让编译器自动确定等代码中的模板参数

class caller2 : public caller <__something_with_function_prototype__> {
    caller2 : caller (function) {};
};

类似的问题是:是否可以用另一个模板类而不是函数来实现这一点?

template <typename T_ret, typename... T_args> class example;
typedef example<int, int> example_t;

谢谢。

不确定这是否是您想要的,但可能是:

#include <iostream>
int function (int arg) { return arg; }
typedef int (*function_t) (int arg);
template <typename T_ret, typename... T_args> 
class caller {
    T_ret (*m_p) (T_args... args);
public:
    T_ret call (T_args... args) {
        return m_p(args...);
    }
    caller (T_ret (*p)(T_args...args)) : m_p(p) {}
};
template <typename T_ret, typename... T_args>
caller<T_ret, T_args...> get_caller(T_ret(*prototype)(T_args...))
{
    return caller<T_ret, T_args...>(prototype);
}
int main()
{
    function_t f = &function;
    auto c = get_caller(f);
    std::cout << c.call(1) << std::endl;
    return 0;
}

实时演示链接。

或者:

#include <iostream>
int function (int arg) { return arg; }
typedef int (*function_t) (int arg);
template <typename T> 
class caller {};
template <typename T_ret, typename... T_args> 
class caller<T_ret(*)(T_args...)> {
    T_ret (*m_p) (T_args... args);
public:
    T_ret call (T_args... args) {
        return m_p(args...);
    }
    caller (T_ret (*p)(T_args...args)) : m_p(p) {}
};
int main()
{
    caller<decltype(&function)> c(&function);
    std::cout << c.call(1) << std::endl;
    return 0;
}

还有另一个现场演示链接。

您可以使用一些助手:

template <typename F> struct helper;
template <typename T_ret, typename... T_args>
struct helper<T_ret (*) (T_args... args)>
{
    using type = caller<T_ret, T_args...>;
};

然后像一样使用

int function (int arg);
class caller2 : public helper<decltype(&function)>::type {
public:
    caller2() : caller (&function) {}
};

更通用:

template <typename T_ret, typename... T_args>
struct helper<T_ret (*) (T_args... args)>
{
    template <template <typename, typename...> class C>
    using type = C<T_ret, T_args...>;
};

然后

class caller2 : public helper<decltype(&function)>::type<caller> {
public:
    caller2() : caller (&function) {}
};

因此CCD_ 1是CCD_ 2