【问题标题】:Template function on struct members结构成员上的模板函数
【发布时间】:2018-01-22 12:24:56
【问题描述】:

有没有办法编写一个能够在给定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;
}

我设想了一个基于开关的答案,但我想知道这个开关是在运行时(我想避免的)还是在编译时进行测试?

【问题讨论】:

  • 你为什么需要那个?
  • 我正在求解一个二维网格的耦合偏导数方程系统,我想为每个单元的所有物理量提供一个空间导数函数......或者至少减少要复制/过去的功能数量!
  • 看起来是多余和麻烦的可能是XY问题。

标签: c++ templates struct switch-statement


【解决方案1】:

只要你想从一组相同类型的数据成员中取出一个数据成员,你可以使用指向数据成员的指针:

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

出于好奇,第二个 sn-p 在 C++17 中会更简单:

template <auto M>
void cout_member(Foo foo)
{
    std::cout << (foo.*M) << std::endl;
}

wandbox 上查看并运行它;

【讨论】:

  • 谢谢!我要 C++17 版本!
  • 当然!很抱歉,我几个小时前就尝试过了,但我花了很长时间才明白该怎么做……现在可以了吗?
【解决方案2】:

您可以利用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 &lt;&lt; obj.fun() 的开销,甚至为零。

编辑:mem_fn 也适用于数据成员。创建一个可调用对象,返回对您可以使用的值的引用:int x = mem_fn(&amp;pair&lt;int,char&gt;::first)(my_pair);

【讨论】:

  • 很公平。我误解了答案。谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
  • 2021-09-11
  • 1970-01-01
相关资源
最近更新 更多