结构成员上的模板函数
Template function on struct members
有没有办法编写能够在给定struct
的不同成员上运行的单个模板函数?
一个错误的例子看起来像:
struct Foo
{
int a, b;
}
template <MEMBER x> //which does not exist
cout_member(Foo foo)
{
cout << foo.x << endl;
}
int main()
{
Foo foo;
cout_member<a>(foo);
cout_member<b>(foo);
return 0;
}
我想象了一个基于开关的答案,但随后我想知道这个开关是否会在运行时(我想避免(或编译时进行测试?
只要要从一组具有相同类型的数据成员中选取数据成员,就可以使用指向数据成员的指针:
template <int Foo::*M>
void cout_member(Foo foo)
{
std::cout << (foo.*M) << std::endl;
}
并将其用作:
cout_member<&Foo::a>(foo);
如果还想指示类型,可以执行以下操作:
template <typename T, T Foo::*M>
void cout_member(Foo foo)
{
std::cout << (foo.*M) << std::endl;
}
并将其用作:
cout_member<int, &Foo::a>(foo);
只是出于好奇,第二个片段在 C++17 中会更简单:
template <auto M>
void cout_member(Foo foo)
{
std::cout << (foo.*M) << std::endl;
}
看到它在魔杖盒上启动并运行;
您可以利用std::mem_fn
,因此您甚至不必关心:(未经测试(
template < typename Fun, typename ... Params >
void print(Fun f, Params && ... p) { std::cout << f(std::forward<Params>(p)...) << "n"; }
print(std::mem_fn(&Obj::fun), Obj());
由于您使用的是流,因此您可能不在乎...但这应该不会从仅写入cout << obj.fun()
中增加很少或零开销。
编辑:mem_fn
也适用于数据成员。 创建一个可调用对象,该对象返回对随后可以使用的值的引用:int x = mem_fn(&pair<int,char>::first)(my_pair);
相关文章:
- 如何使用指针传递给函数的数组中对象的函数成员
- c++构造函数成员初始化:传递参数
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 如何在C++通过公共函数访问私有函数成员?
- 解释了构造函数成员初始化列表
- 调用std::函数成员时内存损坏
- 是否可以为模板类的模板函数成员设置别名?
- 捕获 lambda 函数C++成员变量
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 获取与在模板参数中传递的函数成员类型相同的类
- 如何从公共函数成员访问地图私有成员
- C 构造函数成员分配优化
- 使用命名空间进行函数成员定义
- 函数成员作为 CUDA 内核的参数
- 模板基类函数成员的别名
- 函数成员中用于void和继承的enable_if
- 头文件中是否定义了一个很长的Class函数成员
- 类内/构造函数成员初始化
- 使用指向部分专用函数成员的指针自动填充向量
- 指向函数成员的指针