I'm trying to deduce the types of a class's constructor's parameters. I've succeeded in getting the parameter types for member methods but my approach fails for constructors because it relies on getting the type of a pointer to the member method.
#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");
It's forbidden to obtain the address of a constructor, but I only want to know the type that pointer would have.
You do not specify a return type for a constructor. A return statement in the body of a constructor cannot have a return value. Note: This document describes the syntax, semantics, and IBM z/OS® XL C/C++ implementation of the C and C++ programming languages.
A constructor is a special type of member function that is called automatically when an object is created. In C++, a constructor has the same name as that of the class and it does not have a return type. For example, class Wall { public: // create a constructor Wall() { // code } };
There is no way to refer to a constructor as a function. The standard very explicitly states that constructors have no names. You can't take the address of a constructor.
An alternative might be to require of any type to be used with some machinery, that it has an associated traits type that provides tuples or something corresponding to the constructors.
Before we got language support for decltype
as I recall the Boost functionality for finding the result type of a function relied on a registration scheme for possible types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With