Reputation: 1033
I need to define a function, the function takes two parameters, the first is a container which contains some containers of type T, the second is an integer, the function's signature may look like this:
#include <vector>
#include <string>
#include <list>
using namespace std;
vector<vector<T>> my_function(const vector<vector<T>>& var, int cnt);
vector<list<T>> my_function(const list<vector<T>>& var, int cnt);
how should I define the function template?
Upvotes: 3
Views: 139
Reputation: 366
I have shared some code which defined the functions in a neater and readable manner.
template <typename T>
class MyClass {
typedef vector <T> ContainerVecT;
typedef list <T> ContainerListT;
typedef vector <ContainerVecT> MyContainerVecT;
typedef vector <ContainerListT> MyContainerListT;
MyContainerVecT my_function(const MyContainerVecT& var, int cnt);
MyContainerListT my_function(const MyContainerListT& var, int cnt);
};
Please let me know if it does not satisfy your requirement. We will work on that.
Upvotes: 0
Reputation: 206707
You can define the function as:
template<template<class> class outer,
template<class> class inner,
class element>
outer<inner<element>> my_function(
const outer<inner<element>>& var, int cnt) {
outer<inner<element>> ret;
(void)var, (void)cnt;
return ret;
}
However, you cannot call the function with the following lines:
std::vector<std::vector<int>> v;
my_function(v, 0);
or
my_function<std::vector, std::vector, int>(v, 0);
since std::vector
is defined using more than one template parameter. One work around to that problem is to use:
template <typename T>
using MyVector = std::vector<T>;
Then, you can call:
MyVector<MyVector<int>> v;
my_function<MyVector, MyVector, int>(v, 0);
Still trying to figure out why
MyVector<MyVector<int>> v;
my_function(v, 0);
doesn't work.
Upvotes: 0
Reputation: 45684
This does what you say you want.
Now, you know what kind of containers might be used, and you might even be able to do something worthwhile with it...
#include <vector>
template<class X> class Y{};
template<template<class outer, class... x>
class inner, template<class element, class... x> class outer,
class element, class... x>
inner<outer<element, x...>, x...>
my_function(const outer<inner<element>>& var, int cnt) {
inner<outer<element, x...>, x...> ret;
(void)var, (void)cnt;
return ret;
}
int main() {
#if 1
const std::vector<std::vector<int>> x;
#else
const Y<Y<int>> x{};
#endif
my_function(x, 0);
}
Coliru: http://coliru.stacked-crooked.com/a/bb06e39c799e3b5e
Further reading: Template Template Parameters
Upvotes: 1