C++获取构造函数的类型

C++ obtaining the type of a constructor

本文关键字:类型 构造函数 获取 C++      更新时间:2023-10-16

我试图推断类构造函数参数的类型。我已经成功地获取了成员方法的参数类型,但我的方法对于构造函数失败了,因为它依赖于获取指向成员方法的指针的类型。

#include <tuple>
#include <type_traits>
// Some type with a constructor
struct foo {
    foo(int, double) {}
    void test(char, char) {};
};
// Extract the first parameter
template<class T>
struct func_traits {};
template<class Return, class Type, class ... Params>
struct func_traits<Return(Type::*)(Params...)> {
    using params = std::tuple<Params...>;
};
// Get the parameters for foo::test
using test_type = decltype(&foo::test);
using test_params = typename func_traits<test_type>::params;
static_assert(std::is_same<test_params, std::tuple<char, char>>::value, "Not the right tuple");
// Get the parameters for foo::foo
using ctor_type = decltype(&foo::foo);  // Forbidden
using ctor_type = typename func_traits<ctor_type>::params;
static_assert(std::is_same<ctor_type, std::tuple<int, double>>::value, "Not the right tuple");
禁止

获取构造函数的地址,但我只想知道指针的类型

  • 有没有另一种方法可以确定这种指针的类型?
  • 否则,有没有另一种获取构造函数类型的方法?

有一个解决方案允许您获取构造函数参数类型。

注意:它发现第一个 ctor 具有明确且最短的参数集。

看看我这里的例子:https://godbolt.org/z/FxPDgU

在您的示例中,语句 refl::as_tuple<foo> 将导致std::tuple<int, double> 。拥有此元组类型后,您可以随心所欲地使用foo类型实例化。

上面的代码基于一种解决方案,用于确定用于聚合初始化扩展以处理用户定义的 ctor 的类型。

相关资料:

  1. http://alexpolt.github.io/type-loophole.html

    https://github.com/alexpolt/luple/blob/master/type-loophole.h

    作者:亚历山大·波尔塔夫斯基,http://alexpolt.github.io

  2. https://www.youtube.com/watch?v=UlNUNxLtBI0

    更好的C++14反思 - 安东尼·波卢欣 - 2018 C++会议

没有办法将构造函数称为函数。该标准非常明确地指出构造函数没有名称。不能采用构造函数的地址。

另一种方法是要求任何类型的机器一起使用,它具有提供元组或与构造函数对应的相关特征类型。

在我们获得对decltype的语言支持之前,我记得用于查找函数结果类型的 Boost 功能依赖于可能类型的注册方案。