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

C++ member function template using template

本文关键字:成员 函数模板 C++      更新时间:2023-10-16

很抱歉混淆了标题。我不知道该怎么说。榜样应该自己解释。

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

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;

类型1类型2&Type3是灰泥,和这里的Type3一样使用。INDEX数字不能在结构内,因为可能存在另一个具有不同数字但具有相同类型对象的类型映射。所以类型映射适用于类集合向量中结构的不同顺序,因为顺序对我来说很重要。

接下来是非模板类,它将Type1-3作为属性。我想做的是将这些属性插入到向量中,这是在std::函数的帮助下完成的。但我需要使用一般的类型映射,并将其用作插入向量的索引。

我认为唯一可行的是使用更多的模板。类似于下一段代码,但这不是正确的方式,由于我对模板还是新手,我需要帮助来正确地编写它,因此函数体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参数也有一些模板参数。对不起,我的英语不是母语。也很抱歉".."这与我的问题无关,它会扰乱代码。

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参数,所以我删除了它。

与其为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 s并返回不同的int_ s。:

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>)] = ...;
  }