[英]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.