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;
类型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>)] = ...;
}
相关文章:
- 是否可以获取成员函数模板参数的拥有对象?
- 实例化多种类型的成员函数模板
- C++:递归成员函数模板
- C++成员函数模板将成员函数指针作为模板参数
- 类和成员函数模板专用化出错
- 调用类模板的成员函数模板
- 课堂中成员函数模板的明确实例
- 专用和/或重载具有可变参数的成员函数模板
- 具有可变参数的类成员函数模板部分专用化
- 将 PIMPL 习惯用法与成员函数模板一起使用(无需预先了解所有可能的数据类型)
- 澄清了使用 enable_if 的成员函数模板专用化
- 是否可以从指向成员函数模板参数的指针推断类类型
- 成员函数模板推演指南或其他方法让编译器知道如何调用函数
- 成员函数模板不会在 clang 上编译,但在 GCC 上编译
- 类模板的成员函数模板找不到定义,尽管存在显式实例化。不链接
- 成员函数模板参数的部分专业化
- 在C++中创建成员函数模板专用化
- 要求派生类提供成员函数模板
- 实例化错误后成员函数模板的专业化,以及成员函数的顺序
- 使用提升::函数的成员函数模板