Ziz*_*Tai 2 c++ templates c++11 c++14
是否可以编写一个模板来提取类可转换为的函数指针类型的返回类型和参数类型,只知道类本身?例:
struct Foo {
using FnPtr = int (*)(char, double);
operator FnPtr() const { ... }
};
// Can I extract the return type (int) and argument types (char and double),
// knowing only `Foo` as an opaque type?
Run Code Online (Sandbox Code Playgroud)
如果Foo没有任何其他转换运算符并且没有定义间接运算符,那么您可以依赖于*a_foo将提供对所需类型的函数的引用的事实.从那里,你只需要提取返回和参数.
func_ref_traits 这里将进行提取:
template <typename Func>
struct func_ref_traits;
template <typename Ret, typename... Args>
struct func_ref_traits<Ret(&)(Args...)> {
using ret = Ret;
using args = std::tuple<Args...>;
};
Run Code Online (Sandbox Code Playgroud)
然后conv_func_traits将计算出给定类型的函数类型:
template <typename T>
using conv_func_traits = func_ref_traits<decltype(*std::declval<T>())>;
Run Code Online (Sandbox Code Playgroud)
你会像这样使用它:
conv_func_traits<Foo>::args //std::tuple<char,double>
conv_func_traits<Foo>::ret //int
Run Code Online (Sandbox Code Playgroud)