简体   繁体   English

如何将C ++宏转换为typedef?

[英]How to convert C++ macros to typedefs?

Is there is a typedef equivalent to: 是否有一个typedef等效于:

#define HashTabOf(i)    htab[i]

and

#define MAXCODE(n_bits) (((code_int) 1 << (n_bits)) - 1)

?

The code is in the process of being ported from C to C++. 该代码正在从C移植到C ++的过程中。

Not typedef, but the c++ way is: 不是typedef,但是c ++的方式是:

template <typename T>
inline T &HashTabOf(size_t i)
{
    return htab[i];
}

and

inline size_t MAXCODE(size_t n_bits)
{
    return (1 << n_bits) - 1;
}

I would implement @Dani's template solution as: 我将实现@Dani的模板解决方案为:

inline auto & HashTabOf(size_t i) -> decltype(htab[0])
{
    return htab[i];
}

It is valid only in C++11. 仅在C ++ 11中有效。 It uses a feature called trailing-return-type introduced by C++11. 它使用了C ++ 11引入的称为拖尾返回类型的功能。

The good thing about this solution is that it is not a template anymore. 这个解决方案的好处是它不再是模板。 You don't need to mention T when you use it, while in @Dani's solution you have to mention T as well: 使用时无需提及T ,而在@Dani的解决方案中,您也必须提及T

auto item = HashTabOf<Type>(4); //Dani's solution 
auto item = HashTabOf(4);       //My solution

And yes, you can simply write this: 是的,您可以简单地编写以下代码:

inline int & HashofTable(size_t i)
{ 
   return htab[i]; 
}

Also, why don't you use htab[i] directly? 另外,为什么不直接使用htab[i]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM