命名类成员模板函数的实例

Name Instances of Class Member Template Function

本文关键字:函数 实例 成员      更新时间:2023-10-16

考虑一下这段代码,它显然不起作用,但说明了我想做什么。

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);

我的类有 10 个成员函数,可以采用 2 个值,而不是类型模板参数,我想给它们不同的名称,这样用户就不必输入模板参数。上面的onetwo说明了这一点。

知道如何用 C++17 甚至 C++20 做到这一点吗?

更新:

下面的答案不错,但如前所述有点冗长。我试图避免:

void one(float v) { 
f<1>(v); 
} 

虽然我的实际陈述会稍微长一些。

希望有一些简洁的东西。

不能直接为成员函数添加别名。但是你可以编写转发给他们的包装器:

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...); }

来了,上线了

编写起来有点冗长,但确实为客户端程序员提供了所需的简单性。

如果您接受调用one并使用稍微不同的语法two

(c.*one)(4.0f);
(c.*two)(77.0f);

您可以将onetwo声明为(如果需要,可以称为常量(指向C方法的指针。

我的意思是。。。外面C你可以写

using mftype = void(C::*)(float);
constexpr mftype one = &C::f<1>;
constexpr mftype two = &C::f<2>;

以下是完整的编译示例

#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);
}