Reputation: 885
Consider this code which obviously doesn't work but illustrates what I want to do.
struct C {
template <int I>
void f(float x) {...}
...
using one = f<1>;
using two = f<2>;
};
C c;
c.one(4.0f);
c.two(77.0f);
There a 10 member functions for my class that can take 2 value, not type, template parameters and I want to give them distinct names so the user doesn't have to type in the template parameters. This is illustrated by one
and two
above.
Any ideas how to do this with C++17, or even C++20?
Update:
Nice answer below but as mentioned a bit verbose. I'm trying to avoid:
void one(float v) {
f<1>(v);
}
although my actual statements would be slightly longer.
Hoped something concise was available.
Upvotes: 2
Views: 75
Reputation: 66200
If you accept to call one
and two
with a little different syntax
(c.*one)(4.0f);
(c.*two)(77.0f);
you can declare one
and two
as (constant, if you want) pointers to methods of C
.
I mean... outside C
you can write
using mftype = void(C::*)(float);
constexpr mftype one = &C::f<1>;
constexpr mftype two = &C::f<2>;
The following is a full compiling example
#include <iostream>
struct C
{
template <int I>
void f (float x)
{ std::cout << (x+I) << std::endl; }
};
using mftype = void(C::*)(float);
constexpr mftype one = &C::f<1>;
constexpr mftype two = &C::f<2>;
int main ()
{
C c;
(c.*one)(4.0f);
(c.*two)(77.0f);
}
Upvotes: 2
Reputation: 170064
You can't alias member functions directly. But you can write wrappers that forward to them:
template<typename... Args>
decltype(auto) one(Args&& ...args) { return f<1>((Args&&)args...); }
template<typename... Args>
decltype(auto) two(Args&& ...args) { return f<2>((Args&&)args...); }
A little verbose to write, but does provide the simplicity you want for the client programmer.
Upvotes: 3