none
How can I Use macro to define different datatypes depend on parameter? RRS feed

  • Question

  • define MYPTR(n) if((n)==16?(USHORT*):(BYTE*))

    What I want to do is, if n==16 then "MYPTR(n) pData;" should equal to "USHORT* pData". Otherwise it should be "BYTE* pData"

    but it did not work.I really don't know how to do it.Help plz.

    Friday, December 13, 2019 3:33 AM

Answers

  • What's `n` here? If it's a variable whose value is only known at runtime, then it ain't gonna work - types need to be known at compile time.

    If `n` is a compile-time constant, then a slightly different syntax could be made to work:

    #include <type_traits> template <std::size_t n> using MYPTR = std::conditional_t<n == 16, USHORT*, BYTE*>;

    const int n = 16;

    MYPTR<n> pData;




    Igor Tandetnik

    • Marked as answer by 过往成焰 Friday, December 13, 2019 5:30 AM
    Friday, December 13, 2019 4:31 AM

All replies

  • What's `n` here? If it's a variable whose value is only known at runtime, then it ain't gonna work - types need to be known at compile time.

    If `n` is a compile-time constant, then a slightly different syntax could be made to work:

    #include <type_traits> template <std::size_t n> using MYPTR = std::conditional_t<n == 16, USHORT*, BYTE*>;

    const int n = 16;

    MYPTR<n> pData;




    Igor Tandetnik

    • Marked as answer by 过往成焰 Friday, December 13, 2019 5:30 AM
    Friday, December 13, 2019 4:31 AM
  • thanks!!  and  I use n as a runtime variable,so it is impossible to use macro to define it?
    Friday, December 13, 2019 5:22 AM
  • You must remember that macros are text replacement which occurs before a source file is compiled. So if there was a way to get a macro defined that could choose between types it would still be a compile time thing and require a compile time definition of n.

    As Igor rightfully stated, C++ types need to be known at compile time, and there are very few ways of setting or changing the type of something at runtime.

    C++17 has std::variant and C has unions which you could use for this but you have no way to avoid having two code paths, one for each type.


    This is a signature. Any samples given are not meant to have error checking or show best practices. They are meant to just illustrate a point. I may also give inefficient code or introduce some problems to discourage copy/paste coding. This is because the major point of my posts is to aid in the learning process.

    • Edited by Darran Rowe Friday, December 13, 2019 5:33 AM
    Friday, December 13, 2019 5:32 AM
  • learned, thanks!!!
    Friday, December 13, 2019 5:40 AM