C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 根据模板参数选择联合成员大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在处理C中的联合,我希望有一个函数模板,它可以根据模板参数访问活动的union成员.

代码就像(doSomething只是一个例子):

union Union {
  int16_t i16;
  int32_t i32;
};

enum class ActiveMember {
    I16,I32
}

template <ActiveMember M>
void doSomething(Union a,const Union b) {
  SELEctMemeber(a,M) = SELEctMember(b,M);
  // this would be exactly (not equivalent) the same
  // that a.X = b.X depending on T.
}

为了实现这一点,我只发现了一些糟糕的黑客攻击,比如专业化,或者是一种不同类的访问和分配方式.

我错过了什么,这样的事情应该用其他方法来做?

解决方法

可能性1

而不是使用枚举,您可以使用简单的结构来选择成员:

typedef short int16_t;
typedef long int32_t;

union Union {
    int16_t i16;
    int32_t i32;
};

struct ActiveMemberI16 {};
struct ActiveMemberI32 {};

template <typ@R_944_8371@ M>
void doSomething(Union& a,Union b) {
    SELEctMember(a,M()) = SELEctMember(b,M());

    // this would be exactly (not equivalent) the same
    // that a.X = b.X depending on T.
}

int16_t& SELEctMember(Union& u,ActiveMemberI16)
{
    return u.i16;
}

int32_t& SELEctMember(Union& u,ActiveMemberI32)
{
    return u.i32;
}

int main(int argc,char* argv[])
{
    Union a,b;
    a.i16 = 0;
    b.i16 = 1;
    doSomething<ActiveMemberI16>(a,b);
    std::cout << a.i16 << std::endl;

    b.i32 = 3;
    doSomething<ActiveMemberI32>(a,b);
    std::cout << a.i32 << std::endl;
    return 0;
}

这需要为union中的每个成员定义struct和SELEctMember方法,但至少可以在许多其他函数中使用SELEctMember.

请注意,我将参数转换为引用,如果不合适,您可以调整它.

可能性2

通过将union指针强制转换为所需的类型指针,您可以使用单个SELEctMember函数.

typedef short int16_t;
typedef long int32_t;

union Union {
    int16_t i16;
    int32_t i32;
};
template <typ@R_944_8371@ T>
T& SELEctMember(Union& u)
{
    return *((T*)&u);
}

template <typ@R_944_8371@ M>
void doSomething(Union& a,Union b) {
    SELEctMember<M>(a) = SELEctMember<M>(b);

    // this would be exactly (not equivalent) the same
    // that a.X = b.X depending on T.
}



int _tmain(int argc,_TCHAR* argv[])
{
    Union a,b;
    a.i16 = 0;
    b.i16 = 1;

    doSomething<int16_t>(a,b);
    std::cout << a.i16 << std::endl;

    b.i32 = 100000;
    doSomething<int32_t>(a,b);
    std::cout << a.i32 << std::endl;
    return 0;
}

大佬总结

以上是大佬教程为你收集整理的c – 根据模板参数选择联合成员全部内容,希望文章能够帮你解决c – 根据模板参数选择联合成员所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。