In C++, not every thing is an object. A function could take anything, and not everything in C++ is an object. So it's going to be difficult to make a runtime deduction if some random thing being passed to a function is a vector
or something completely unrelated. Moreover, it's going to be impossible to declare a function that can take anything, without resorting to void*
(please don't), a template
, or some kind of variant
object.
However we can take advantage of a little template metaprogramming to deduce it at compile time:
#include <cstdlib>
#include <vector>
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
template <typename Type>
class IsArray;
template<typename Element> class IsArray <vector <Element>>
{
public:
enum { mValue = true };
};
template<typename Item> class IsArray
{
public:
enum { mValue = false };
};
int main()
{
int n = 42;
cout << "An int is a vector: " << boolalpha << IsArray<int>::mValue << endl;
vector <int> v;
cout << "A vector <int> is a vector: " << boolalpha << IsArray<vector<int>>::mValue << endl;
}
Output:
An int is a vector: 0
A vector <int> is a vector: 1
Actually, this could be simplified further to appear like we're making the deduction at runtime even though it's still being made at compile time:
#include <iostream>
#include <vector>
using namespace std;
template <typename Element> bool IsArray (const vector <Element>& vec)
{
return true;
}
template <typename Item> bool IsArray (const Item& item)
{
return false;
}
int main()
{
int n = 42;
cout << "An int is a vector: " << boolalpha << IsArray (n) << endl;
vector <int> v;
cout << "A vector <int> is a vector: " << boolalpha << IsArray (v) << endl;
}
Output is the same.