如何将数据成员名称作为参数传递给另一个参数?

时间:2015-08-01 01:01:16

标签: c++ function templates parameter-passing generic-programming

给出这样的结构:

struct Foo{
    std::string name;
    int value;
};

我正在寻找一种方法来传递类型的实例化,
以及数据成员名称,
每个作为单独的参数。

虽然这是不正确的语法,但我认为它有助于说明我想要实现的目标:

template<typename MemberName>
void Print(Foo foo, MemberName member_name){
    std::cout << foo.member_name << '\n';  
}

int main(){

    Foo foo{"name",100}; //create instance

    Print(foo,.name);  //prints name
    Print(foo,.value); //prints 100
}

如何在C ++中实现?

此外,我无权修改该类型的减速度。

1 个答案:

答案 0 :(得分:6)

您可能正在寻找指向会员的指示:

#include <string>
#include <iostream>

struct Foo{
  std::string name;
  int value;
};

template<typename MemberType>
void Print(Foo foo, MemberType Foo::* member_name){
  std::cout << foo.*member_name << '\n';  
}

int main(){

  Foo foo{"name",100}; //create instance

  Print(foo, &Foo::name);  //prints name
  Print(foo, &Foo::value); //prints 100
}

编辑:当然,指向成员的指针在c ++中并不常见,在这种特定情况下,只需传递Steephen建议的实际成员值就更好了(但也许你想在更复杂的情况下使用它们) )