why are struct/union childs of global not allowed as template reference parameter - but the globals itself?

StackOverflow https://stackoverflow.com/questions/11222519

  •  17-06-2021
  •  | 
  •  

Question

I try to reference to an child element of an global variable by using an template parameter - it does work for globals but not for childs of globals - why is the position resolving of an child not possible at compile-time?

typedef unsigned char byte_t;
typedef unsigned short word_t;

struct byte_reg_t
{
     byte_t low;
     byte_t high;
};

union word_reg_t
{
     word_t value;
     byte_reg_t part;
};

word_t rax;
byte_t rah;
word_reg_t r16;
byte_reg_t r8;

template<typename ValueType, ValueType& Ref>
ValueType ret_ref()
{
     return Ref;
}

int main()
{
    word_t x = ret_ref<word_t,rax>();
    byte_t h = ret_ref<byte_t,rah>();
    //word_t sx = ret_ref<word_t,r16.value>(); // compile error
    //byte_t sh = ret_ref<byte_t,r16.part.low>(); // compile error
    //byte_t sh2 = ret_ref<byte_t,r8.low>(); // compile error

    return 0;
} 

the VS2010 and clang 3.1 compiler does not allow the // compile error lines

thx for any clear description because i don't see any technical reason for that behavior of the compilers

Was it helpful?

Solution

The answer lies in the C++ Standard. Sorry for being outdated, but my version (ISO/IEC 14882, 2nd Ed. 2003) says (page 246):

§14.3.2 Template non-type arguments

   [..]

3 [Note: Addresses of array elements and names or addresses of non-static class members are not acceptable template-arguments.[..]]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top