如何获取构造函数的元数?(注:元数即参数个数)

4

如果有一个模板参数类T,它只有一个构造函数(没有复制或移动构造函数),并且没有默认参数,是否有某种方法可以找到T(...)的元数?

到目前为止,我的尝试:

#include <iostream>
#include <string>
#include <vector>

template <typename F> struct function_arity;

template <typename R, typename... Args>
struct function_arity<R (Args...)>
    : std::integral_constant<std::size_t, sizeof...(Args)> {};

template <typename R, typename... Args>
struct function_arity<R (*)(Args...)> : function_arity<R (Args...)> {};

template <typename R, typename... Args>
struct function_arity<R (&)(Args...)> : function_arity<R (Args...)> {};

template <typename R, typename C, typename... Args>
struct function_arity<R (C::*)(Args...) const> : function_arity<R (Args...)> {};

template <typename R, typename C, typename... Args>
struct function_arity<R (C::*)(Args...)> : function_arity<R (Args...)> {};

template <typename C>
struct function_arity : function_arity<decltype(&C::operator())> {};

struct no_copy { no_copy() = default; no_copy(const no_copy&) = delete; };
struct no_move { no_move() = default; no_move(no_move&&) = delete; };

struct A : no_copy, no_move { A(int, float) { std::cout << "A!\n"; }; };
struct B : no_copy, no_move { B(double) { std::cout << "B!\n"; }; };
struct C : no_copy, no_move { C() { std::cout << "C!\n"; }; };

int main()
{
    std::cout << function_arity<&A::A>::value << "\n";
    return 0;
}

仍然存在复制构造函数... - Jarod42
@Jarod 不,它和移动构造函数都被标记为已删除。只有一个构造函数可用。 - Brian Rodriguez
@BrianRodriguez:我的意思是删除的函数是重载的一部分演示 - Jarod42
@Jarod 那这就是不可能的吗? - Brian Rodriguez
@BrianRodriguez 如果类型已知,那是可能的。 - Columbo
@Columbo 嗯,类型理论上应该是静态已知的(这就是我将要使用它的方式)。你是说当我尝试推断它们时,我必须明确列出类型吗?那样会有点违背我的目标... - Brian Rodriguez
1个回答

3

如果我们做出以下假设:

  • 参数要么是固定的类型,要么是完全不受限制的catch-all参数(例如不包括std::basic_string<CharT>
  • 参数是可移动构造的

那么,

#include <type_traits>
#include <utility>

namespace detail {
    template <typename Ignore>
    struct anything {
        template <typename T,
                  typename=std::enable_if_t<not std::is_same<Ignore, std::decay_t<T>>{}>>
        operator T&&();
    };

    template <typename U, typename=void, typename... args>
    struct test : test<U, void, args..., anything<U>> {};
    template <typename U, typename... args>
    struct test<U, std::enable_if_t<std::is_constructible<U, args...>{}
                                 && sizeof...(args) < 32>, args...>
        : std::integral_constant<std::size_t, sizeof...(args)> {};
    template <typename U, typename... args>
    struct test<U, std::enable_if_t<sizeof...(args) == 32>, args...>
        : std::integral_constant<std::size_t, (std::size_t)-1> {};
}

template <typename U>
using ctor_arity = detail::test<U, void>;

…应该按预期工作。演示
请注意,上述方法很容易转换为C++11。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接