繁体   English   中英

使用模板的C ++成员函数模板

[英]C++ member function template using template

抱歉混淆的标题。 我不知道怎么说。 示例应该解释自己。

我发现了一种叫做类型映射的东西,并将它用于我的代码,如下所示:

template<typename T>
struct typemap
{
    static const int INDEX;
};

template<>
const int typemap<Type1>::INDEX = 1;
template<>
const int typemap<Type2>::INDEX = 3;
template<>
const int typemap<Type3>::INDEX = 11;

Type1 Type2和Type3是stucts,在这里使用类似的类型。 INDEX号不能在struct中,因为可能有另一个具有不同数字但具有相同type-object的typemap。 因此,typemap适用于像vector这样的集合中的不同顺序,因为顺序对我很重要。

接下来是非模板类,它将Type1-3作为属性。 而我正在尝试做的是将这些属性插入到vector中,这是在std :: function的帮助下完成的。 但我需要采用通用的typemap并将其用作索引以插入到vector。

我认为唯一可行的是使用更多模板。 像下一个代码的东西,但这是不正确的方式,因为我还是模板的新手,我需要帮助才能正确编写它,因此函数体toVector开始按需要工作。

class MyClass
{
  Type1 type1_;
  Type2 type2_;
  Type3 type3_;
  ..

  template<typename T>
  void toVector(T& typemap)
  {
    std::vector<..> vect;
    vect.resize(..);
    vect[typemap<Type1>::INDEX] = type1_.someFunction(..);
    vect[typemap<Type2>::INDEX] = type2_.someFunction(..);
  }

};

我确定我使用模板错误的成员函数,我不知何故需要说T参数也有一些模板参数。 对不起我的英语,不是母语。 也很抱歉“..”它与我的问题无关,它会弄乱代码。

我们不是为INDEX添加显式特化,而是创建一个可以传递的实际对象类型typemap 首先是一些样板:

template <class T>
struct tag_type {
    using type = T;
};

template <class T>
constexpr tag_type<T> tag{};

template <int I>
using int_ = std::integral_constant<int, I>;

现在,我们为index()创建一个带有一堆重载的对象,它接受不同的tag_type并返回不同的int_

struct typemap {
    constexpr int_<3> size() const { return {}; }

    constexpr int_<1> index(tag_type<Type1> ) const { return {}; }
    constexpr int_<3> index(tag_type<Type2> ) const { return {}; }
    constexpr int_<11> index(tag_type<Type3> ) const { return {}; }
};

这是你可以传递给函数模板的东西,只需使用:

  template<typename T>
  ??? toVector(T const& typemap)
  {
      std::vector<..> vect;
      vect.resize(typemap.size());

      vect[typemap.index(tag<Type1>)] = ...;
      vect[typemap.index(tag<Type2>)] = ...;
      vect[typemap.index(tag<Type3>)] = ...;
  }

Barry的回答是更好的方法来做你想做的事情,但是这里有关于你有一个模板参数的具体问题的答案,模板参数本身就是一个带有一个参数的模板:

  template<template<typename> class type_with_one_template_parameter>
  void toVector()
  {
    std::vector<..> vect;
    vect.resize(..);
    vect[type_with_one_template_parameter<Type1>::INDEX] = type1_.someFunction(..);
    vect[type_with_one_template_parameter<Type2>::INDEX] = type2_.someFunction(..);
  }

不清楚为什么函数在原始示例中有T& typemap参数,所以我删除了它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM