I can imagine the following code:
template class X
{
public:
T container;
void foo()
{
if(is_vector(T))
contain
An alternative worth considering is to detect the presence of the push_back function using SFINAE. This is slightly more generic since it'll translate to other containers that implement push_back.
template
struct has_push_back
{
template
static std::true_type test(
decltype((void(U::*)(const typename U::value_type&)) &U::push_back)*);
template
static std::false_type test(...);
typedef decltype(test(0)) type;
static constexpr bool value =
std::is_same::value;
};
Note that it currently only detects push_back(const T&)
and not push_back(T&&)
. Detecting both is a little more complicated.
Here's how you make use of it to actually do the insert.
template
void push_back_impl(C& cont, const T& value, std::true_type) {
cont.push_back(value);
}
template
void push_back_impl(C& cont, const T& value, std::false_type) {
cont.insert(value);
}
template
void push_back(C& cont, const T& value) {
push_back_impl(cont, value, has_push_back::type());
}
std::vector v;
push_back(v, 1);
std::set s;
push_back(s, 1);
Honestly, this solution became a lot more complicated then I originally anticipated so I wouldn't use this unless you really need it. While it's not too hard to support const T&
and T&&
, it's even more arcane code that you have to maintain which is probably not worth it in most cases.