Home > Software design >  Alias function template
Alias function template

Time:06-02

I want to be able to do the equivalent of this:

template <class T>
void foo(int i=42) {
  // ... do stuff and use T for something ...
}

using ifoo= foo<int>; // <-- This is the part I am looking for

int main() {
  ifoo();
}

Is there any way to do something like this?

CodePudding user response:

You can use a function pointer:

auto ifoo = &foo<int>;

Note that the & is optional (ie you can also write auto ifoo = foo<int>;). auto gets deduced as void (*)().

CodePudding user response:

The simplest solutions are usually the best:

void ifoo()
{
   foo<int>();
}

compiler should optimize this so ifoo and foo<int> just shares code.

CodePudding user response:

you can create a reference (alias) to the specific function.

auto& ifoo= foo<int>;

or alias the whole template (technically one-by-one)

template <typename T>
auto& fooT = foo<T>;

https://godbolt.org/z/nqbKfnfhe (with some more examples)

  • Related