有没有人曾经使用过C++的"贴牌新品"?如果是这样,那该怎么办?在我看来,它只对内存映射硬件有用.
我不明白为什么我会这样做:
struct S {
int a;
S(int aa) : a(aa) {}
S() = default;
};
Run Code Online (Sandbox Code Playgroud)
为什么不说:
S() {} // instead of S() = default;
Run Code Online (Sandbox Code Playgroud)
为什么要为此引入一个新关键字?
如果它是a struct那么就可以完成
*p = {var1, var2..};
Run Code Online (Sandbox Code Playgroud)
但似乎这不起作用union:
union Ptrlist
{
Ptrlist *next;
State *s;
};
Ptrlist *l;
l = allocate_space();
*l = {NULL};
Run Code Online (Sandbox Code Playgroud)
只得到:
expected expression before ‘{’ token
Run Code Online (Sandbox Code Playgroud) 我很惊讶这不起作用:
union DlDatum
{
float mFloat;
s32 mInteger;
};
class DlDbE
{
public:
DlDbE( float f ) : mData.mFloat( f ) {};
private:
DlDatum mData;
};
Run Code Online (Sandbox Code Playgroud)
有没有办法在c ++构造函数mem-initializer列表中初始化union?
更新:答案是为union创建构造函数.不知道可以做到的.这是我做的:
union DlDatum
{
float mFloat;
s32 mInteger;
bool mBoolean;
u32 mSymbol;
u32 mObjIdx;
DlDatum( ) : mInteger( 0 ) {}
DlDatum( float f ) : mFloat( f ) {}
DlDatum( s32 i ) : mInteger( i ) {}
DlDatum( bool b ) : mBoolean( b ) {}
DlDatum( u32 s ) …Run Code Online (Sandbox Code Playgroud) 给定一个类如下面的一个类和给定的union,如何将union初始化为正确的值?
这里尝试的是使用两种或更多种不同类型作为该类的核心数据类型之一.考虑到提前知道类型,将构造将要使用的类型的并集,而不是使用void*.问题是如何在实例化类时初始化正确的union成员.类型不是多态的,因此通常的继承模型似乎不合适.一些天真的尝试初始化正确的工会成员无处可去.
union Union {
int n;
char *sz;
};
class Class {
public:
Class( int n ): d( 1.0 ), u( n ) {}
Class( char *sz ): d( 2.0 ), u( sz ) {}
....
double d;
Union u;
};
Run Code Online (Sandbox Code Playgroud)
在寻找解决方案之后,答案变得明显,并且可能是这个答案库的一个很好的解决方案,所以我将其包含在下面.
我有一个Result<T>模板类,它包含一些error_type和的联合T.我想在不借助虚函数的情况下公开基类中的公共部分(错误).
这是我的尝试:
using error_type = std::exception_ptr;
struct ResultBase
{
error_type error() const
{
return *reinterpret_cast<const error_type*>(this);
}
protected:
ResultBase() { }
};
template <class T>
struct Result : ResultBase
{
Result() { new (&mError) error_type(); }
~Result() { mError.~error_type(); }
void setError(error_type error) { mError = error; }
private:
union { error_type mError; T mValue; };
};
static_assert(std::is_standard_layout<Result<int>>::value, "");
void check(bool condition) { if (!condition) std::terminate(); }
void f(const ResultBase& alias, Result<int>& r)
{ …Run Code Online (Sandbox Code Playgroud) class Foo {
Foo(int val) { /* Do some initialization */ }
Foo() { /* Do nothing */ }
};
union Bar {
Foo foo;
};
Run Code Online (Sandbox Code Playgroud)
该代码生成此错误:
错误C2620:union'Bar'的成员'Bar :: foo'具有用户定义的构造函数或非平凡的默认构造函数
我明白为什么如果构造函数实际执行某些操作会抛出该错误,但这里的构造函数不带参数而什么也不做.有什么办法可以把这个班级变成一个联盟吗?我不得不一直采取行动,char foo[sizeof(Foo)]并希望有一个更清洁的解决方案.