命名类成员模板函数的实例
Name Instances of Class Member Template Function
考虑一下这段代码,它显然不起作用,但说明了我想做什么。
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 个值,而不是类型模板参数,我想给它们不同的名称,这样用户就不必输入模板参数。上面的one
和two
说明了这一点。
知道如何用 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);
您可以将one
和two
声明为(如果需要,可以称为常量(指向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);
}
相关文章:
- 如何在c++中为模板函数实例创建快捷方式
- 如何使用非默认构造函数实例化模板化类
- C++ - 使用另一个类的构造函数实例化一个对象
- 结构数组的构造函数错误,错误消息:没有构造函数实例与参数列表匹配
- 与参数匹配的友元模板函数实例化
- c++如何获取模板函数实例的地址
- 在保证复制的世界中构造函数实例化
- SFINAE 和模板函数实例化:为什么在启用了 SFINAE 类型的函数参数中使用模板参数时无法推断模板参数?
- 防止复制构造函数实例化 C++11 类"deleting"
- 如何键入定义一个专门的 std::set 模板,使用特定的比较函数实例化
- 没有 std::string .erase() 的重载函数实例
- C 矢量构造函数实例冲突
- 确保只有一个函数实例在运行?
- 使用不同类型的模板函数实例化
- C 调用模板构造函数实例化
- 没有与参数列表错误匹配的重载函数" "实例
- 为什么很清楚模板函数实例化不会内联
- 没有unordered_map的模板函数实例
- 模板函数实例化文件
- 模板函数实例化的可移植性问题