草庐IT

C++ 检查构造函数是否包含给定类型的参数

coder 2024-02-04 原文

使用 std::is_constructible 可以质疑某个给定类型是否存在某个构造函数:

struct A {};
struct B
{
     explicit B(int, A, double) {}
};

int main()
{
    std::cout<<std::is_constructible<B,int,A,double>::value<<std::endl; //prints true
}

假设一个人不知道类型B。还有一种方法可以检查 B 中是否存在包含类型 A 的构造函数,而不考虑其他参数? (或者,已经足够了,在第 n 个位置包含类型 A?)


给定一个非显式构造函数,我通过使用可以隐式转换为任何类型的类型找到了一个解决方法:

struct convert_to_anything
{
    template<typename T>
    operator T() const
    {
        return T{};    
    }
};

int main()
{
    std::cout<<std::is_constructible<B, convert_to_anything, A, convert_to_anything>::value<<std::endl;
}

(实际上,出乎我意料的是,我根据经验发现,当 explicit 被添加到 B 的构造函数中时,它似乎也能正常工作......而我认为它会阻止转换?)

尽管如此,使用此变通方法我将不得不测试所有可能的参数数量。对于第一个位置的 A 说:

std::is_constructible<B, A>::value
|| std::is_constructible<B, A, convert_to_anything>::value
|| std::is_constructible<B, A, convert_to_anything, convert_to_anything>::value
//... and so on up to a chosen maximum size.

这似乎有点不令人满意。您有更好的解决方法吗?

最佳答案

不,基本上没有其他方法可以做到这一点。正如您所建议的,可以使用编译时元编程来手动展开排列。我相信下面的通用实现已经尽可能好了。请参阅代码底部的 has_constructor_taking 别名模板及其用法。

下面的代码使用了我描述的template_worm 技术here ,这是您的 convert_to_anything 的更充实的实现。该代码适用于最新版本的 Clang 和 GCC。

#include <utility>
#include <type_traits>
#include <tuple>

namespace detail {

    //template_worm CANNOT be used in evaluated contexts
    struct template_worm {

        template<typename T>
        operator T& () const;

        template<typename T>
        operator T && () const;

        template_worm() = default;

        template<typename... T>
        template_worm(T&&...);

        template_worm operator+() const;
        template_worm operator-() const;
        template_worm operator*() const;
        template_worm operator&() const;
        template_worm operator!() const;
        template_worm operator~() const;
        template_worm operator()(...) const;
    };

#define TEMPLATE_WORM_BINARY_OPERATOR(...)                                 \
                                                                           \
    template<typename T>                                                   \
    constexpr inline auto                                                  \
    __VA_ARGS__ (template_worm, T&&) -> template_worm {                    \
        return template_worm{};                                            \
    }                                                                      \
                                                                           \
    template<typename T>                                                   \
    constexpr inline auto                                                  \
    __VA_ARGS__ (T&&, template_worm) -> template_worm {                    \
        return template_worm{};                                            \
    }                                                                      \
                                                                           \
    constexpr inline auto                                                  \
    __VA_ARGS__ (template_worm, template_worm) -> template_worm {          \
        return template_worm{};                                            \
    }                                                                      \
    /**/

    TEMPLATE_WORM_BINARY_OPERATOR(operator+)
    TEMPLATE_WORM_BINARY_OPERATOR(operator-)
    TEMPLATE_WORM_BINARY_OPERATOR(operator/)
    TEMPLATE_WORM_BINARY_OPERATOR(operator*)
    TEMPLATE_WORM_BINARY_OPERATOR(operator==)
    TEMPLATE_WORM_BINARY_OPERATOR(operator!=)
    TEMPLATE_WORM_BINARY_OPERATOR(operator&&)
    TEMPLATE_WORM_BINARY_OPERATOR(operator||)
    TEMPLATE_WORM_BINARY_OPERATOR(operator|)
    TEMPLATE_WORM_BINARY_OPERATOR(operator&)
    TEMPLATE_WORM_BINARY_OPERATOR(operator%)
    TEMPLATE_WORM_BINARY_OPERATOR(operator,)
    TEMPLATE_WORM_BINARY_OPERATOR(operator<<)
    TEMPLATE_WORM_BINARY_OPERATOR(operator>>)
    TEMPLATE_WORM_BINARY_OPERATOR(operator<)
    TEMPLATE_WORM_BINARY_OPERATOR(operator>)

    template<typename T>
    struct success : std::true_type {};

    template<typename T, typename... Args>
    struct try_construct {
        static constexpr bool value = std::is_constructible<T, Args...>::value;
    };

    template<typename T>
    struct try_construct<T, void> {

        template<typename U>
        static auto test(int) ->
            success<decltype(U())>;

        template<typename>
        static std::false_type test(...);

        static constexpr const bool value = decltype(test<T>(0))::value;
    };

    template<typename T, typename ArgTuple, typename MappedSeq>
    struct try_construct_helper;

    template<typename T, typename ArgTuple, std::size_t... I>
    struct try_construct_helper<T, ArgTuple, std::index_sequence<I...>> {
        using type = try_construct<T, typename std::tuple_element<I, ArgTuple>::type...>;
    };

    struct sentinel {};

    template<typename Target>
    using arg_map = std::tuple<Target, template_worm const &>;

    constexpr const std::size_t MappedTargetIndex = 0;
    constexpr const std::size_t MappedWormIndex = 1;

    template<std::size_t>
    using worm_index = std::integral_constant<std::size_t, MappedWormIndex>;

    template<typename SeqLeft, typename SeqRight>
    struct map_indices;

    template<std::size_t... Left, std::size_t... Right>
    struct map_indices<std::index_sequence<Left...>, std::index_sequence<Right...>> {

        using type = std::index_sequence<
            worm_index<Left>::value...,
            MappedTargetIndex,
            worm_index<Right>::value...
        >;
    };

    template<std::size_t... Right>
    struct map_indices<sentinel, std::index_sequence<Right...>> {
        using type = std::index_sequence<0, worm_index<Right>::value...>;
    };

    template<std::size_t... Left>
    struct map_indices<std::index_sequence<Left...>, sentinel> {
        using type = std::index_sequence<worm_index<Left>::value..., 0>;
    };

    template<>
    struct map_indices<sentinel, sentinel> {
        using type = std::index_sequence<0>;
    };

    template<std::size_t IncrementBy, typename Seq>
    struct increment_seq;

    template<std::size_t IncrementBy, std::size_t... I>
    struct increment_seq<IncrementBy, std::index_sequence<I...>> {
        using type = std::index_sequence<(I + IncrementBy)...>;
    };

    // Checks the U constructor by passing TargetArg in every argument slot recursively
    template<typename U, typename TargetArg, std::size_t TargetIndex, std::size_t Max, typename SeqOrSentinel>
    struct try_constructors;

    template<typename U, typename TargetArg, std::size_t TargetIndex, std::size_t Max>
    struct try_constructors<U, TargetArg, TargetIndex, Max, sentinel> {
        static constexpr const bool value = false;
    };

    template<typename U, typename TargetArg, std::size_t TargetIndex, std::size_t Max, std::size_t... I>
    struct try_constructors<U, TargetArg, TargetIndex, Max, std::index_sequence<I...>> {

        using next = typename std::conditional<
            sizeof...(I)+1 <= Max,
            std::make_index_sequence<sizeof...(I)+1>,
            sentinel
        >::type;

        using args = arg_map<TargetArg>;

        using left_seq = typename std::conditional<
            TargetIndex == 0,
            sentinel,
            std::make_index_sequence<TargetIndex>
        >::type;

        using right_seq_detail = typename increment_seq<
            TargetIndex,
            std::make_index_sequence<sizeof...(I)-TargetIndex>
        >::type;

        using right_seq = typename std::conditional<
            TargetIndex == (sizeof...(I)),
            sentinel,
            right_seq_detail
        >::type;

        using mapped_seq = typename map_indices<left_seq, right_seq>::type;

        static constexpr const bool value = std::disjunction<
            typename try_construct_helper<U, args, mapped_seq>::type,
            try_constructors<U, TargetArg, TargetIndex, Max, next>
        >::value;
    };

    // unrolls the constructor attempts using the argument counts in the SearchSeq range
    template<typename T, typename TargetArg, typename SearchSeq>
    struct try_constructors_outer;

    template<typename T, typename TargetArg, std::size_t... TargetIndices>
    struct try_constructors_outer<T, TargetArg, std::index_sequence<TargetIndices...>> {

        static constexpr const bool value = std::disjunction<
            try_constructors<
                T,
                TargetArg,
                TargetIndices,
                sizeof...(TargetIndices),
                std::make_index_sequence<TargetIndices>
            >...
        >::value;
    };

    template<typename T, std::size_t... TargetIndices>
    struct try_constructors_outer<T, void, std::index_sequence<TargetIndices...>> {
        static constexpr const bool value = try_construct<T, void>::value;
    };
}

// Here you go.
template<typename TargetArg, typename T, std::size_t SearchLimit = 4>
using has_constructor_taking = std::integral_constant<bool,
    detail::try_constructors_outer<
        T,
        TargetArg,
        std::make_index_sequence<SearchLimit>
    >::value
>;

struct A {};

struct B {
    B(int, A, double) {}
};

struct C {
    C() = delete;
    C(C const &) = delete;
};

static_assert(has_constructor_taking<A, B>::value, "");
static_assert(has_constructor_taking<int, B>::value, "");
static_assert(has_constructor_taking<double, B>::value, "");
static_assert(!has_constructor_taking<C, B>::value, "");
static_assert(!has_constructor_taking<const char*, B>::value, "");

static_assert(has_constructor_taking<void, A>::value, "");
static_assert(has_constructor_taking<A const &, A>::value, "");

static_assert(!has_constructor_taking<void, C>::value, "");
static_assert(!has_constructor_taking<C const &, C>::value, "");

int main() {}

关于C++ 检查构造函数是否包含给定类型的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29735942/

有关C++ 检查构造函数是否包含给定类型的参数的更多相关文章

  1. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  2. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  3. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  4. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  5. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  6. ruby - 检查数组是否在增加 - 2

    这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

  7. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  8. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  9. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  10. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

随机推荐