detecting typedef at compile time (template metaprogramming)

后端 未结 4 1238
悲&欢浪女
悲&欢浪女 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:40

    You can create a trait has_const_iterator that provides a boolean value and use that in the specialization.

    Something like this might do it:

    template 
    struct has_const_iterator {
    private:
        template 
        static typename T1::const_iterator test(int);
        template 
        static void test(...);
    public:
        enum { value = !std::is_void(0))>::value };
    };
    

    And then you can specialize like this:

    template ::value,
              bool HasConstIterator = has_const_iterator::value>
    struct Foo; // default case is invalid, so no definition!
    
    template 
    struct Foo< T, true, false>{ 
       void do_stuff(){// bla }
    };
    
    template
    struct Foo {
        void do_stuff(){//bla}
    };
    

提交回复
热议问题