确定未定义函数的参数类型
Determining the Parameter Types of an Undefined Function
我最近了解到我不能:
- 获取未定义函数的地址
- 获取一个模板化函数的地址,该函数的类型将无法编译
但我最近也了解到,我可以调用decltype
来获得所述函数的返回类型
因此,一个未定义的函数:
int foo(char, short);
我想知道是否有一种方法可以将参数类型与tuple
中的类型相匹配。这显然是一个元编程问题。在这个例子中,我真正想拍摄的是类似decltypeargs
的东西:
enable_if_t<is_same_v<tuple<char, short>, decltypeargs<foo>>, int> bar;
有人能帮我理解decltypeargs
是如何制作的吗?
对于非重载函数、指向函数的指针和指向成员函数的指针,只需执行decltype(function)
即可在未赋值的上下文中获得函数的类型,并且该类型包含所有参数。
因此,要将参数类型作为元组,您只需要进行大量专业化:
// primary for function objects
template <class T>
struct function_args
: function_args<decltype(&T::operator()>
{ };
// normal function
template <class R, class... Args>
struct function_args<R(Args...)> {
using type = std::tuple<Args...>;
};
// pointer to non-cv-qualified, non-ref-qualified, non-variadic member function
template <class R, class C, class... Args>
struct function_args<R (C::*)(Args...)>
: function_args<R(Args...)>
{ };
// + a few dozen more in C++14
// + a few dozen more on top of that with noexcept being part of the type system in C++17
有了这个:
template <class T>
using decltypeargs = typename function_args<T>::type;
这需要您编写decltypeargs<decltype(foo)>
。
有了C++17,我们将有template <auto>
,所以上面可以是:
template <auto F>
using decltypeargs = typename function_args<decltype(F)>::type;
你会得到decltypeargs<foo>
语法。
相关文章:
- 扩展C++生成的代码的模板参数类型名称
- 如何在 c++ 中定义接受不同参数类型的函数向量?
- 在 C++ 中运行时调用模板时,是否可以切换模板的参数类型?
- 将函数参数类型声明为 auto
- 将函数的参数 - 签名从使用 'std::function<T>' 转换为模板参数类型
- 在 C++17 中调用具有不同参数类型的构造函数
- 具有先前参数类型匹配的参数包
- 我想知道为什么"std::unique_ptr<int> foo(新 int)"是合法的,因为"std::<int>unique_ptr"要求输入参数类型应该是"int"?
- 将可变参数类型列表的扩展打包为复杂类型的初始值设定项列表 - 合法吗?
- MSVC 错误:4 个重载中的任何一个都无法转换所有参数类型
- 使用constexpr + auto作为返回和参数类型的奇怪类型推导
- 如何从第一个参数推断第二个参数类型?
- C++模板函数中,指定回调函子/lambda 的参数类型,同时仍允许内联?
- 如何用不同的参数类型和数字回调函数
- C++stoi:这两个重载都无法转换所有参数类型
- 为什么std::{container}::template不能推导其参数类型
- 为模板参数类型中的新对象分配内存
- 为指向成员模板参数的指针推导额外模板参数类型的紧凑方式
- 使用std::conditional中的模板来确定函数参数类型
- C++中的短参数类型