gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:39 24 4
gpt4 key购买 nike

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

#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类型实例化。

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

相关资料:

  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 反射(reflection) - Antony Polukhin - Meeting C++ 2018

关于C++获取构造函数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41623899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com