Disambiguate template specialization between map-like and vector-like containers

前端 未结 3 660
孤独总比滥情好
孤独总比滥情好 2021-01-01 18:43
template struct Printer;

// I want this to match std::vector (and similar linear containers) 
template class T, clas         


        
3条回答
  •  盖世英雄少女心
    2021-01-01 19:44

    The problem here is that

    template  T
    

    and

    template  TM
    

    both match any template classes that have at least 2 template parameters which is the case in both your examples. One thing you can do is to make both template parameter lists more specific, like for example:

    template 
    struct Printer;
    
    template  class C, template  class A, typename T>
    struct Printer< C> > {
        ...
    };
    
    template  class C, template  class Comp, template  class A, typename K, typename T>
    struct Printer< C, A>> > {
        ...
    };
    

    You can see it working for std::vector and std::map here: http://coliru.stacked-crooked.com/a/7f6b8546b1ab5ba9

    Another possibility is to use SFINAE (actually I'd recommend using it in both scenarios):

    template class T, class TV, class... TS, class = typename std::enable_if::value>::type> 
    struct Printer> { ... };
    
    template class TM, class TK, class TV, typename... TS, class = typename std::enable_if::value>::type> 
    struct Printer> { ... }
    

    Edit: Oups, just read in the comments you wanted to match something 'std::vector'-like, not specifically std::vector. The first method however should at least differentiate between std::vector and std::map. If you want to write algorithms for containers with different ways to iterate over, why not write your functions for iterators and differentiate between those?

    Edit2: The code before was miserably wrong. However it works now.

提交回复
热议问题