我试图找到一种更优雅的方式来读取和编写结构,而不是将它们转换为void指针,然后将大小传递给函数,如下所示:
power=* in "Provincie Antwerpen"
所以我试图创建一个方法来隐式地将任何类型转换为如下所示的结构:
FindAll
然后我可以(假设我可以找到一种方法从任何其他类型隐式转换为此类型)创建良好的读写函数,如下所示:
Dim SearchRange As Range, FindWhat As Variant, FoundCells As Range, FoundCell As Range
FindWhat = Array("Country1","Country2","Country3",etc)
Set SearchRange = ActiveSheet.Range("B:B")
For s = LBound(FindWhat) to UBound(FindWhat)
Set FoundCells = FindAll(SearchRange:=SearchRange, FindWhat:=FindWhat(s), LookIn:=xlValues,LookAt:=xlWhole, MatchCase:=False)
If Not FoundCells Is Nothing Then
For each FoundCell In FoundCells
FoundCell.Offset(,-1).Value = FoundCell.Value
Next
End If
Next s
不幸的是,我能找到从任何其他类型转换为此类型的唯一方法是使VoidPtrReplacement成为模板化结构。我不想这样做,因为我创建的任何使用这个结构的编写函数也必须模板化。
所以我的问题是:我可以创建一个隐式转换函数,它不是任何结构或类的一部分(或者如果有更好的方法可以做到这一点)吗?
答案 0 :(得分:2)
您不需要模板化结构,只需要模板化构造函数。像这样:
#include <iostream>
#include <vector>
struct VoidPtrReplacement{
const unsigned char *bytes;
size_t size;
template<typename T>
VoidPtrReplacement(T &&t)
: bytes(reinterpret_cast<unsigned char *>(&t)),
size(sizeof(T))
{
}
};
void write(const VoidPtrReplacement &p)
{
std::cout << "Write: " << (void *)p.bytes << ", " << p.size << " bytes"
<< std::endl;
}
class Foo {
int i=4;
};
class Bar {
char c=0;
int b=3;
};
int main()
{
Foo foo;
Bar bar;
std::cout << "Address of foo: " << &foo << std::endl;
std::cout << "Address of bar: " << &bar << std::endl;
write(foo);
write(bar);
}
示例输出:
Address of foo: 0x7ffd5eba4c80
Address of bar: 0x7ffd5eba4c60
Write: 0x7ffd5eba4c80, 4 bytes
Write: 0x7ffd5eba4c60, 8 bytes