【发布时间】: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