detecting typedef at compile time (template metaprogramming)

后端 未结 4 1236
悲&欢浪女
悲&欢浪女 2021-02-03 10:06

I am currently doing some template metaprogramming. In my case I can handle any \"iteratable\" type, i.e. any type for which a typedef foo const_iterator exists in

4条回答
  •  佛祖请我去吃肉
    2021-02-03 10:55

    There is a couple of ways to do this. In C++03, you could use boost and enable_if to define the trait (docs, source):

    BOOST_MPL_HAS_XXX_TRAIT_DEF(const_iterator);
    
    template 
    struct Foo;
    
    template 
    struct Foo< T, typename boost::enable_if >::type>{ 
       void do_stuff(){ ... }
    };
    
    template
    struct Foo >::type> {
        void do_stuff(){ ... }
    };
    

    In C++11, you could use Tick like this:

    TICK_TRAIT(has_const_iterator)
    {
        template
        auto require(const T&) -> valid<
            has_type
        >;
    };
    
    template 
    struct Foo;
    
    template 
    struct Foo< T, TICK_CLASS_REQUIRES(std::is_fundamental::value)>{ 
       void do_stuff(){ ... }
    };
    
    template
    struct Foo())> {
        void do_stuff(){ ... }
    };
    

    Also with Tick you can further enhance the trait to actually detect that the const_iterator is actually an iterator, as well. So say we define a simple is_iterator trait like this:

    TICK_TRAIT(is_iterator,
        std::is_copy_constructible<_>)
    {
        template
        auto require(I&& i) -> valid<
            decltype(*i),
            decltype(++i)
        >;
    };
    

    We can then define has_const_iterator trait to check that the const_iterator type matches the is_iterator trait like this:

    TICK_TRAIT(has_const_iterator)
    {
        template
        auto require(const T&) -> valid<
            has_type>
        >;
    };
    

提交回复
热议问题