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

问题描述 投票:4回答:2

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

#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");

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

  • 还有另一种方法来确定这种指针的类型吗?
  • 否则,是否有另一种获取构造函数类型的方法?
c++ templates type-deduction
2个回答
5
投票

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

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

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


1
投票

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

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

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

在您的示例中,语句refl::as_tuple<foo>将导致std::tuple<int, double>。一旦你有这个元组类型,你可以随心所欲,包括foo类型实例化。

上面的代码基于一个解决方案,用于确定用于处理用户定义的ctors的aggregate-init扩展的类型。

相关材料:

  1. http://alexpolt.github.io/type-loophole.html https://github.com/alexpolt/luple/blob/master/type-loophole.h 作者:Alexandz Poltavsky,http://alexpolt.github.io
  2. https://www.youtube.com/watch?v=UlNUNxLtBI0 更好的C ++ 14反思 - Antony Polukhin - Meeting C ++ 2018
© www.soinside.com 2019 - 2024. All rights reserved.