c++ - 如何在类中使用成员函数特化?

标签 c++ templates

#include <iostream>
#include <string>

using namespace std;

struct Uid {
  typedef int type;  
};

struct Name {
  typedef string type;
};


struct Age {
  typedef int type;
};


template <class T1, class T2, class T3>
class People {
private:
  typename T1::type val1;
  typename T2::type val2;
  typename T3::type val3;
  //add a get function here
  }
};


int main() {
  People<Uid, Name, Age> people;
  people.get<Uid>(); //make this validate
}

这是我的代码,我想在类中添加一个 get 函数,以使函数调用 get 在 main validate 中。 我尝试在类中添加模板 get 及其特化版本,但这是一种无效方法,编译者说:在非命名空间范围“类 People”中显式特化。有人说这个方法在vs中可以用,但是违反了标准。

最佳答案

您需要一个模板化 get() 成员函数可以使用的辅助类。辅助类可以位于命名空间范围内。

#include <iostream>
#include <string>

using std::string;
using std::cout;

struct Uid {
  typedef int type;
};

struct Name {
  typedef string type;
};

struct Age {
  typedef int type;
};

// Helper class that can be specialized to get different members of People.
template <class P, class U> struct PeopleGet;


template <class T1, class T2, class T3>
class People {
public:
  People(
    typename T1::type const& val1,
    typename T2::type const& val2,
    typename T3::type const& val3
  )
  : val1(val1),
    val2(val2),
    val3(val3)
  {
  }

  template <class U> typename U::type get()
  {
    return PeopleGet<People<T1,T2,T3>,U>::get(*this);
  }
private:
  typename T1::type val1;
  typename T2::type val2;
  typename T3::type val3;

  template <class P,class U> friend class PeopleGet;
};


template <class T1,class T2,class T3>
struct PeopleGet<People<T1,T2,T3>,T1> {
  static typename T1::type get(const People<T1,T2,T3> &people)  { return people.val1; }
};

template <class T1,class T2,class T3>
struct PeopleGet<People<T1,T2,T3>,T2> {
  static typename T2::type get(const People<T1,T2,T3> &people)  { return people.val2; }
};

template <class T1,class T2,class T3>
struct PeopleGet<People<T1,T2,T3>,T3> {
  static typename T3::type get(const People<T1,T2,T3> &people)  { return people.val3; }
};


int main()
{
  People<Uid, Name, Age> people(5,"name",47);
  cout << people.get<Uid>() << "\n";
  cout << people.get<Name>() << "\n";
  cout << people.get<Age>() << "\n";
  return 0;
}

关于c++ - 如何在类中使用成员函数特化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12327804/

相关文章:

c++ - GDI+ 绘制成束的字母

c++ - 编译错误 : could not deduce template argument

c++ - 使用模板元编程 C++ 比较 2 个值

c++ - 带有 C++ 模板的虚假 "use of local variable with automatic storage from containing function"?

c++ - Enterprise Architect 中的模型模板功能

c++ - 在使用指向 const 和非常量方法的成员指针时减少模板特化的数量

c++ - Pango Span 文本中的新符号颜色

c++ - 如果在派生类中将私有(private)虚函数重写为公共(public)函数,会出现什么问题?

c++ - 为什么 lambda 转换为值为 true 的 bool?

c++ - 如何获得除法中带有十进制数的结果? C++, 树莓派