使用模板来克服缺少基类?

ove*_*der 5 c++ templates std

显然,标准容器没有公共基类,也没有通用接口,尽管方法名称是同构的.

问题:我必须用一组独特类型的对象填充容器.容器可以是a std::list,a std::vector或a std::deque,也可能是其他一些自定义容器.以下代码是最佳解决方案吗?

# include <string>
# include <iostream>
# include <list>
# include <vector>
# include <deque>

/*
 * Fill a container with two strings. The container
 * must expose the `clear` and `push_back` methods.
 */
template<typename T>
void f(T & t)
{
    t.clear() ;

    t.push_back("Alice") ;
    t.push_back("Bob") ;
}

int main(int, char*[])
{
    std::list<std::string>    l ;
    std::vector<std::string>  v ;
    std::deque<std::string>   q ;

    f(l) ;   // fill the list
    f(v) ;   // fill the vector
    f(q) ;   // fill the double-ended queue

    // possibly anything with `clear` and `push_back` methods
    // can be filled with `f`

    return 0 ;
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的建议!


编辑

这是我f在第一篇文章中说明的情况:

struct AudioFormat
{
    uint32_t   samplerate ;   // Sampling frequency
    uint8_t    channels ;     // The number of channels
    uint8_t    bitdepth ;     // The number of bits per sample
} ;

class AudioDevice
{
    // many stuff skipped
    public :
      /*
       * Fills the container with available audio formats handled properly by the device
       */
      void GetSupportedAudioFormats(std::list<AudioFormat> &) ;
    // many stuff skipped
} ;
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种更好的声明方式,GetSupportedFormats因此它可以处理许多其他容器,而不仅仅是std::lists.这是我第一篇文章的重点.

Pie*_*BdR 6

我最喜欢的是:

/*
 * Fill a container with two strings. The container
 * must expose the `clear` and `push_back` methods.
 */
template<typename T>
void f(T & t)
{
    t.clear() ;

    std::insert_iterator<T> it(t, t.end());
    *it++ = "Alice";
    *it++ = "Bob";
}
Run Code Online (Sandbox Code Playgroud)

现在的约束是:clearinsert,所以它也可以std::set用于例如.此外,它可以使用任何类型,你只需要专门std::insert_iterator为它的模板.