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

时间:2017-01-12 22:10:29

标签: 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");

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

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

2 个答案:

答案 0 :(得分:5)

无法将构造函数作为函数引用。该标准非常明确地指出构造函数没有名称。你不能拿构造函数的地址。

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

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

答案 1 :(得分:1)

有一个解决方案可以让您获取构造函数参数类型。

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

在这里查看我的示例:https://godbolt.org/z/FxPDgU

在您的示例中,语句refl::as_tuple<foo>将导致std::tuple<int, double>。一旦有了该元组类型,就可以随便选择,包括foo类型实例化。

以上是基于用于确定用于类型的溶液中的代码骨料-INIT延伸到手柄用户定义构建函数。

相关材料:

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

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

    Alexander Poltavsky着,http://alexpolt.github.io

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

    更好的C ++ 14思考-安东尼·波卢欣(Antony Polukhin)-Meeting C ++ 2018