Reputation: 381
I am wondering if it is possible to have a template alias as a function input type, and the 'further' type can be further determined based on the input?
template<typename T>
using Vec = std::vector<T>;
I want to define a function:
void func(Vec& a){
for(auto &each :a){
//Do something
}
}
Where the type of Vec
can be derived based on the input a
.
In such an example, the same func
can be applied to all a
as std::vector<ANY TYPE>
.
I have such an issue because I have a vec
initialized at the first beginning and run a series of functions.
a = Vec<int>;
fun1(a);
fun2(a);
...
funN(a);
I want to have the same operations but with different types.
a = Vec<double>;
fun1(a);
fun2(a);
...
funN(a);
If I follow the old templated function it will be
a = Vec<int>;
fun1<int>(a);
fun2<int>(a);
...
funN<int>(a);
and to change to double
I have to do
a = Vec<double>;
fun1<double>(a);
fun2<double>(a);
...
funN<double>(a);
Basically, I have to change int
to double
for each function. I am looking forward some easier ways to do so.
Upvotes: 1
Views: 70
Reputation: 14434
Thanks to template argument deduction, templates already behave in the way that you want.
Defining func
as
template<typename T>
void func(Vec<T>& a) {
// ...
}
will let you write
Vec<int> a{};
func(a);
Vec<double> b{};
func(b);
No explicit type parameters are required at the call-site.
Upvotes: 3