c++ - Single template instantiation for separate objects -


consider following:

/* t.h */ template <class t> void too() {     std::cout << "  template: " << typeid(t).name()               << " size: " << sizeof(t) << std::endl; } 
/* a.h */ extern void fooa(); 
/* a.cpp */ struct local {     int a[2]; }  void fooa() {     local l;     std::cout << "<foo a>:\n" << "  real: " << typeid(l).name()               << " size: " << sizeof(l) << std::endl;     too<local>(); } 
/* b.h */ extern void foob(); 
/* b.cpp */ struct local {     int a[4]; };  void foob() {     local l;     std::cout << "<foo b>:\n" << "  real: " << typeid(l).name() \               << " size: " << sizeof(l) << std::endl;     too<local>(); } 
/* main.cpp */ int main() {     fooa();     foob();     return 0; } 

compiling , running results in:

<foo a>:   real: 5local size: 8   template: 5local size: 8 <foo b>:   real: 5local size: 16   template: 5local size: 8 

which means single template instantiation used both template calls. notably -- first one. while possible workaround 'feature' defining too()

template <class t, size_t s = sizeof(t)> too(); 

i wanted know there more generic approaches problem? since above code still fail if 2 calling structures of same size.

edit:

specifically problem lies in fact, can not change files , b. may not introduce anonymous namespaces them. there template side solutions? hence second template parameter.

your program violates odr (one definition rule) containing 2 definitions of struct local. means it's ill-formed , has undefined behaviour, can happen.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -