C++ 定义函数的宏

C++ 定义函数的宏,c++,if-statement,macros,C++,If Statement,Macros,我使用以下宏生成函数代码 #define EXTRACT_INSTRUCTION32_FIELD(insName,fieldName,fieldOffset) \ insName##Instruction::##fieldName val; \ val = static_cast<##insName##Instruction::##fieldName##>((hexIstruction & ##insName##Mask_##fieldName) >&g

我使用以下宏生成函数代码

#define EXTRACT_INSTRUCTION32_FIELD(insName,fieldName,fieldOffset) \
    insName##Instruction::##fieldName val; \
    val = static_cast<##insName##Instruction::##fieldName##>((hexIstruction & ##insName##Mask_##fieldName) >> fieldOffset); \
    return val

我不喜欢这种解决方案,它会降低性能-有人建议hot这样做吗

> P>我倾向于使用更多的C++正确方法来使用内联函数或模板,沿着以下的部分:

template <class T, U, V>
U extractInstruction32Field(T insName, U fieldName, V fieldOffset, W hexInstruction, bool isRet = false)
{
    U retval;
    retval = static_cast<U>((hexInstruction& insName::fieldName) >> fieldOffset);
    if isRet    {   return retval;  }
}
模板
U ExtractInstruction32字段(T insName、U fieldName、V fieldOffset、W hexInstruction、bool isRet=false)
{
U回顾;
retval=静态转换((hexInstruction&insName::fieldName)>>fieldOffset);
如果isRet{return retval;}
}
请注意,
isRet
布尔值默认为false,因此仅当您选择使用它时才会返回值。 在不知道你的掩码(
##mask
)值是什么的情况下,上面的值纯粹是示例性的,我认为它不起作用,但它应该为你指出一条新的途径。
这种方法将允许类型安全和适当的错误检查,而define并不能很好地发挥作用。

您过度使用了
#
操作符,在大多数使用它的地方并不需要它。我甚至不确定在某些地方使用它是否“合法”。为什么要使用
##isRet
,而实际上并没有与任何其他标识符连接?您只需使用
isRet
。类似地,您可以使用
fieldName
而不是
##fieldName
作为总共3种用法中的2种。我不确定您试图实现什么,但我打赌通过使用内联函数和指针可以获得相同的结果,只是更优雅和可读。为什么不使用两个宏呢?返回的可以用不返回的定义。你能确切地说什么是不需要的吗?+1 OP可能还想摆脱解决方案中的
U retval
。雅科夫,你能澄清一下你对返回/不返回的要求吗?(即,在什么条件下要求退货和不退货?)干杯:)
template <class T, U, V>
U extractInstruction32Field(T insName, U fieldName, V fieldOffset, W hexInstruction, bool isRet = false)
{
    U retval;
    retval = static_cast<U>((hexInstruction& insName::fieldName) >> fieldOffset);
    if isRet    {   return retval;  }
}