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

Fra*_*eux 7 c++ templates type-deduction

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

#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");
Run Code Online (Sandbox Code Playgroud)

禁止获取构造函数的地址,但我只想知道指针所具有的类型.

  • 还有另一种方法来确定这种指针的类型吗?
  • 否则,是否有另一种获取构造函数类型的方法?

小智 8

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

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

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

在您的示例中,该语句refl::as_tuple<foo>将导致std::tuple<int, double>. 一旦你有了这个元组类型,你就可以做任何你想要的事情,包括foo type instantiation.

上面的代码基于确定用于扩展聚合初始化以处理用户定义的构造函数的类型的解决方案。

相关材料:

  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 反思 - Antony Polukhin - Meeting C++ 2018


Che*_*Alf 5

无法将构造函数称为函数.该标准非常明确地指出构造函数没有名称.您不能获取构造函数的地址.

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

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