Implementing a compile-time “static-if” logic for different string types in a container

后端 未结 5 1337
南笙
南笙 2020-12-14 21:14

I\'d like to write a function template that operates on a container of strings, for example a std::vector.

I\'d like to support both CString

5条回答
  •  心在旅途
    2020-12-14 22:13

    One common way to solve this is to extract the required interface out into a trait class. Something like this:

    template 
    struct StringTraits
    {
      static size_t size(const S &s) { return s.size(); }
      // More functions here
    };
    
    
    template 
    void DoSomething(const ContainerOfStrings& strings)
    {
        for (const auto & s : strings)
        {
          auto len = StringTraits::type>::size(s);
        }
    }
    
    
    // Anyone can add their own specialisation of the traits, such as:
    
    template <>
    struct StringTraits
    {
      static size_t size(const CString &s) { return s.GetLength(); }
      // More functions here
    };
    

    Of course, you can then go fancy and change the function itself to allow trait selection in addition to the type-based selection:

    template >
    void DoSomething(const ContainerOfStrings& strings)
    

提交回复
热议问题