简体   繁体   中英

Can template alias be used as a function input type?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM