#include <iostream>
#include <type_traits>
#include <utility>
#include <vector>
template <typename Container>
typename std::enable_if <is_iterable <Container> ::value, void> ::type
do_something( const Container & xs )
{
for (auto x : xs)
std::cout << x << "\n";
}
int main()
{
std::vector <int> v = { 2, 3, 5, 7 };
do_something( v );
int n = 42;
do_something( n );
auto p = std::make_pair( 3.14159265, -7 );
do_something( p );
}
C:\Users\Michael\foo> cl /EHsc /W4 /Ox /std:c++17 a.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 19.21.27702.2 for x64
Copyright (C) Microsoft Corporation. All rights reserved.
a.cpp
a.cpp(68): error C2672: 'do_something': no matching overloaded function found
a.cpp(68): error C2893: Failed to specialize function template 'std::enable_if<is_iterable<T>::value,void>::type do_something(const Container &)'
a.cpp(68): note: With the following template arguments:
a.cpp(68): note: 'Container=int'
a.cpp(71): error C2672: 'do_something': no matching overloaded function found
a.cpp(71): error C2893: Failed to specialize function template 'std::enable_if<is_iterable<T>::value,void>::type do_something(const Container &)'
a.cpp(71): note: With the following template arguments:
a.cpp(71): note: 'Container=std::pair<double,int>'
~/baz% clang++ -Wall -Wextra -pedantic-errors -O3 -std=c++17 a.cpp
a.cpp:68:3: error: no matching function for call to 'do_something'
do_something( n );
^~~~~~~~~~~~
a.cpp:56:1: note: candidate template ignored: requirement 'is_iterable<int>::value' was not satisfied
[with Container = int]
do_something( const Container & xs )
^
a.cpp:71:3: error: no matching function for call to 'do_something'
do_something( p );
^~~~~~~~~~~~
a.cpp:56:1: note: candidate template ignored: requirement 'is_iterable<std::pair<double, int> >::value' was not
satisfied [with Container = std::pair<double, int>]
do_something( const Container & xs )
^
2 errors generated.
As you can see, it compiles fine for the vector (or any other iterable standard container), but not for anything else: it complains for the int and the std::pair.
It would be a very elaborate construction;
we would need to check for all the standard container requirements, and there are very many: https://eel.is/c++draft/container.reqmts