我有一堆结构,每个结构都有一个“数组”成员和一个大小指示器:
struct S {
size_t num;
int arr[100];
};
struct V {
float array[10];
int size;
};
我想为每个结构创建操纵器对象:
template <typename Type, typename ElementType, size_t N, typename SizeType>
struct StructManipulator {
Type* resource_;
ElementType Type::*elements[N];
SizeType Type::*sizeIndicator;
void set(ElementType val, size_t idx)
{
resource_->*elements[idx] = val;
}
};
template <typename Type, typename ElementType, size_t N, typename SizeType>
StructManipulator<Type, ElementType, N, SizeType> makeStructManipulator(Type* resource,
ElementType Type::*elements[N], SizeType Type::*sizeIndicator)
{
return StructManipulator<Type, ElementType, N, SizeType>{resource, elements, sizeIndicator};
}
StructManipulator
将让我独立于数组的偏移量和结构内的大小指示符来操作数组元素。全部StructManipulator
是结构中“数组”的偏移量、大小指示符的偏移量和类型以及指向结构对象的指针。
但是,当我尝试创建一个StructManipulator
:
int main()
{
S s;
auto m = makeStructManipulator(&s, &S::arr, &S::num);
m.set(5, 4);
}
我收到此错误:
main.cpp: In function 'int main()':
main.cpp:39:56: error: no matching function for call to 'makeStructManipulator(S*, int (S::*)[100], size_t S::*)'
auto m = makeStructManipulator(&s, &S::arr, &S::num);
^
main.cpp:29:51: note: candidate: template<class Type, class ElementType, long unsigned int N, class SizeType> StructManipulator<Type, ElementType, N, SizeType> makeStructManipulator(Type*, ElementType Type::**, SizeType Type::*)
StructManipulator<Type, ElementType, N, SizeType> makeStructManipulator(Type* resource,
^~~~~~~~~~~~~~~~~~~~~
main.cpp:29:51: note: template argument deduction/substitution failed:
main.cpp:39:56: note: mismatched types 'ElementType Type::**' and 'int (S::*)[100]'
auto m = makeStructManipulator(&s, &S::arr, &S::num);
我看起来无法正确声明“指向数组成员的指针”的类型?正确的声明应该是什么?