C++ 使用模板依赖类型
我试图使用模板对类中的字段进行编码——我正在研究有线协议——但这些模板给我带来了困难。基本上,我希望能够使用模板指定“字段”以及它们应该如何为导线编码(除此之外,我正在简化这个问题)。这是我的尝试,但我得到了一个编译时错误(见下文)——这是不是我对依赖类型名做得不正确C++ 使用模板依赖类型,c++,templates,C++,Templates,我试图使用模板对类中的字段进行编码——我正在研究有线协议——但这些模板给我带来了困难。基本上,我希望能够使用模板指定“字段”以及它们应该如何为导线编码(除此之外,我正在简化这个问题)。这是我的尝试,但我得到了一个编译时错误(见下文)——这是不是我对依赖类型名做得不正确 // Encodes values, but identity for this example template <typename T> struct Encoder { typename T::type op
// Encodes values, but identity for this example
template <typename T>
struct Encoder {
typename T::type operator()(const typename T::type& value) {
return value;
}
};
// Declares the properties of Fields (such as Encoding...)
template <typename T, typename E=Encoder<T>>
struct Field {
typedef T type;
typedef E encoder;
};
// A root for all classes that need Encoded Fields
struct C {
template <typename T>
void set(const typename T::type& value) {
typename T::encoder encode;
encode(value);
}
};
// A mock specific class with 1 Encoded Field
struct H : C {
typedef Field<int> my_field;
};
int main() {
H h;
h.set<H::my_field>(3);
}
//对值进行编码,但本例中的标识
模板
结构编码器{
类型名T::类型运算符()(常量类型名T::类型和值){
返回值;
}
};
//声明字段的属性(例如编码…)
模板
结构域{
T型;
E型编码器;
};
//所有需要编码字段的类的根
结构C{
模板
无效集(常量类型名T::类型和值){
类型名T::编码器编码;
编码(值);
}
};
//具有1个编码字段的模拟特定类
结构H:C{
typedef字段my_字段;
};
int main(){
H;
h、 组(3);
}
编译器错误为:
In instantiation of 'struct Encoder<int>':
required from 'void C::set(const typename T::type&) [ with T = F<int>; typename T::type = int]'
required from here
error: 'int' is not a class, struct or union type
typename T::type operator()(const typename T::type& value) {
在“结构编码器”的实例化中:
“void C::set(const typename T::type&)[with T=F;typename T::type=int]中需要此项”
从这里开始需要
错误:“int”不是类、结构或联合类型
类型名T::类型运算符()(常量类型名T::类型和值){
作为实例化过程的一部分,您制作了一个编码器
。但是编码器有一个成员函数:
typename T::type operator()(const typename T::type& value);
并且您不能计算int::type
,而是基于C::set()
:
这也更具语义意义。编码器
接受一个T
,并返回一些其他的T
。通过该更改,您的代码可以编译
对于依赖类型名称,我是否做得不正确
// Encodes values, but identity for this example
template <typename T>
struct Encoder {
typename T::type operator()(const typename T::type& value) {
return value;
}
};
// Declares the properties of Fields (such as Encoding...)
template <typename T, typename E=Encoder<T>>
struct Field {
typedef T type;
typedef E encoder;
};
// A root for all classes that need Encoded Fields
struct C {
template <typename T>
void set(const typename T::type& value) {
typename T::encoder encode;
encode(value);
}
};
// A mock specific class with 1 Encoded Field
struct H : C {
typedef Field<int> my_field;
};
int main() {
H h;
h.set<H::my_field>(3);
}
对
用于实例化编码器
的类型是int
,而不是字段
将编码器更改为:
template <typename T>
struct Encoder {
T operator()(const T& value) {
return value;
}
};
模板
结构编码器{
T运算符()(常数T和值){
返回值;
}
};
工作正常,但我不确定您是否有其他想法。它告诉您,您正在尝试实例化编码器
,因为字段
是字段
,但是int
没有成员类型
(显然).我不确定有什么不清楚的错误。我想你搞定了-我对类型感到困惑:-(我想你搞定了-我对类型感到困惑:-(
template <typename T>
struct Encoder {
T operator()(const T& value) {
return value;
}
};