64-bit G++ 4.6.3 doesn't treat longs as long longs in specialised function templates, even though they're the same size. Is this a bug?

不羁的心 提交于 2019-12-11 04:54:37

问题


Consider the following code:

#include <iostream>
#include <cinttypes>  

template<class T>
void f();

template<>
inline void f<long long>() {
  std::cout<<"f<long long>()"<<std::endl;
}

int main(int , char** ) {
  std::cout<<"sizeof(long)="<<sizeof(long)<<std::endl;
  std::cout<<"sizeof(long long)="<<sizeof(long long)<<std::endl;
  f<int64_t>();
  return 0;
}

32-bit G++ 4.6.3 compiles this successfully and produces the output:

sizeof(long)=4
sizeof(long long)=8
f<long long>()

Compiling under 64-bit G++ 4.6.3 however produces the linker error:

undefined reference to `void f<long>()'
ld returned 1 exit status

even though compiling and running with the f<int64_t>() line commented out produces:

sizeof(long)=8
sizeof(long long)=8

Is there a good reason why 64-bit G++ treats f<long> and f<long long> as different functions, even though long and long long are the same size, or is this a bug that I should report?


回答1:


The underlying type of int64_t can be anything that meets the requirements. It's okay to make it long on one platform and long long on another.

Since you provide a specialization for long long and the generic version has no body, if int64_t is not a long long you get an undefined reference.

And yes, there is a good reason why f<long> and f<long long> are different functions: it's because the standard says that long and long long are distinct types. The fact that they happen to be the same width on some platform doesn't matter, especially because they may be of different widths on another.




回答2:


They are different types, so they have to be treated differently. The size of the types does not affect overloading or template selection.

Your problem might be that int64_t is long on one system and long long on the other. That's a problem when combining typedefs with overloads or templates.



来源:https://stackoverflow.com/questions/12463402/64-bit-g-4-6-3-doesnt-treat-longs-as-long-longs-in-specialised-function-templ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!