Очевидно, что стандартные контейнеры не имеют ни общего базового класса, ни общего интерфейса, хотя имена методов являются однородными.
Проблема: я должен заполнить контейнер коллекцией объектов уникального типа. Контейнером может быть std::list
, std::vector
или 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 ;
}
Спасибо за любой совет!
EDIT
Вот случай, который я проиллюстрировал 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
} ;
Я ищу лучший способ объявить GetSupportedFormats
, чтобы он мог обрабатывать многие другие контейнеры, не только std::list
s. В этом смысл моего первого поста.