【发布时间】:2015-06-10 01:29:34
【问题描述】:
我正在尝试创建一个模板类,其中包含指向任意类实例和函数的指针,如下所示:
template<class C>
class A {
typedef void (C::*FunctPtr)(); //e.g. void C::some_funct();
FunctPtr functPtr_;
C* instPtr_;
public:
A(FunctPtr functPtr, C* instPtr)
: functPtr_(functPtr)
, instPtr_(instPtr) {}
};
但是,我希望能够创建此类的实例,而无需使用 Placement new 进行动态内存分配。 C++ 标准是否保证该模板类对于所有 C 类都是固定大小的?
在Don Clugston's article 指针中,我注意到各种编译器上成员函数指针的各种大小的图表,并且一些编译器的大小并不总是相同。我以为我被冲洗了,但这个标准符合吗?从 C++ 标准秒。 5.2.10 重新解释演员表:
——将“指向成员函数的指针”类型的纯右值转换为指向成员函数的不同指针 类型并返回其原始类型会产生指向成员值的原始指针。
C++ 标准中的该语句是否表明成员函数指针的大小都相同?
如果不是,我想我仍然可以重写代码,以明确利用 reinterpret_cast 保证:
class GenericClass;
template<class C>
class A {
typedef void (GenericClass::*GenFunctPtr)();
typedef void (C::*SpecificFunctPtr)();
GenFunctPtr functPtr_; //store any kind of function ptr in this fixed format
GenericClass* instPtr_;
public:
A(SpecificFunctPtr functPtr, C* instPtr)
: functPtr_(reinterpret_cast<GenFunctPtr>(functPtr))
, instPtr_(reinterpret_cast<GenericClass*>(instPtr)) {}
void DoSomething()
{
//now convert pointers back to the original type to use...
reinterpret_cast<SpecificFunctPtr>(functPtr_);
reinterpret_cast<C*>(instPtr_);
}
};
现在看来,这似乎需要尺寸相同但符合标准,对吧?我更喜欢第一个选项,但是如果我必须第二个也可以。想法?
【问题讨论】:
-
该标准甚至不保证
C*对于所有C的大小相同(尽管它在必须的平台上)——即使它保证您可以通过void *往返.我还认为它允许任何插入的填充发生变化。如果您想要完全的可移植性,我认为您不走运 - 尽管我认为您的机制将适用于大多数平台。
标签: c++ c++11 delegates standards-compliance reinterpret-cast