c++11 - C++ Template Equivalence of Prototypes -
the following compiles runs , executes expected:
#include <cstdlib> #include <cstring> #include <iostream> #include <type_traits> class freaky { public: template< typename unsigned_type, typename std::enable_if<(sizeof(unsigned_type)>=sizeof(int)),int>::type x = 0 > static unsigned_type copything(int x) ; }; template< typename unsigned_type, typename std::enable_if<(sizeof(unsigned_type)>=sizeof(int)),int>::type x > unsigned_type freaky::copything(int x) { unsigned_type r(0); std::memcpy(&r,&x,sizeof(int));//please ignore. not point of question... return r; } int main(int argc, char*argv[]) { std::cout << "the answer ... " << freaky::copything<unsigned long>(10)<<std::endl; return exit_success; } specimen output (actual output may depend on endian-ness , integer sizes):
the answer .... 10 the following won't compile , complains prototype implementation of copything() doesn't match 1 declared in class.
#include <cstdlib> #include <cstring> #include <iostream> #include <type_traits> class freaky { public: template< typename unsigned_type, typename std::enable_if<(sizeof(unsigned_type)>=sizeof(int)),int>::type x = 0 > static unsigned_type copything(int x) ; }; template< typename unsigned_type, typename std::enable_if<(sizeof(int)<=sizeof(unsigned_type)),int>::type x > unsigned_type freaky::copything(int x) { unsigned_type r(0); std::memcpy(&r,&x,sizeof(int));//please ignore. not point of question... return r; } int main(int argc, char*argv[]) { std::cout << "the answer ... " << freaky::copything<unsigned long>(10)<<std::endl; return exit_success; } the difference between 2 sizeof(unsigned_type)>=sizeof(int) has been replaced sizeof(int)<=sizeof(unsigned_type) in implementation.
obviously 2 statements semantically equivalent. can find formal definition of how template prototypes determined equal?
it's level of lexical equivalence rather semantic equivalence.
i can't find part of standard explicitly specifies when redeclarations of class templates (or class template , specifier in out-of-line definition of members) same.
compilers follow rules redeclaration of function template, specified in c++11 14.5.6.1/5+6:
5 2 expressions involving template parameters considered equivalent if 2 function definitions containing expressions satisfy 1 definition rule (3.2), except [template parameter renaming]. 6 2 function template equivalent if declared in same scope, have same name, have identical template parameter lists, , have return types , parameter lists equivalent using rules described above compare expressions involving template parameters.
i can't find rule makes apply expressions in types of non-type template parameters redeclarations of class templates, though.
Comments
Post a Comment