【问题标题】:C++ obtaining the type of a constructorC++获取构造函数的类型
【发布时间】:2017-05-28 04:38:13
【问题描述】:

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

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

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

  • 是否有其他方法可以确定此类指针的类型?
  • 否则,还有其他方法可以获取构造函数的类型吗?

【问题讨论】:

  • 您现有的代码是否适用于重载函数?
  • @KerrekSB 如果您指定重载,它会起作用,但在这种情况下,您已经知道参数,所以它没有实际意义。我以为我会遇到重载问题,但我还没有做到。
  • 就目前而言,答案是否定的。构造函数没有名称,也无法获取其地址。有人提到了一个想法,即提出一种神奇的类型特征,它将类的构造函数公开为一组函数调用运算符重载,但这还没有(还)在任何地方实现。
  • 你好。你有没有找到从构造函数中提取参数类型的方法?我目前正在做同样的任务。这可能是可能的,因为 Boost.DI 很可能以某种方式做到了。
  • @Sergey.quixoticaxis.Ivanov 我还没有找到实现这一目标的方法。它必须以某种方式由类型提供。我选择了专攻一个特质。

标签: c++ templates type-deduction


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

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

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

    在您的示例中,语句 refl::as_tuple&lt;foo&gt; 将导致 std::tuple&lt;int, double&gt;。一旦你有了这个元组类型,你可以随心所欲,包括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 反射 - Antony Polukhin - Meeting C++ 2018

    【讨论】:

      猜你喜欢
      • 2017-09-14
      • 1970-01-01
      • 1970-01-01
      • 2015-02-23
      • 2012-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多