简体   繁体   中英

How to convert C++ macros to typedefs?

Is there is a typedef equivalent to:

#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++.

Not typedef, but the c++ way is:

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:

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

It is valid only in C++11. It uses a feature called trailing-return-type introduced by 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:

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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