In the following code, I create a Builder
template, and provide a default implementation to return nothing. I then specialize the template with int, to return a value 37.
When I compile with -O0
, the code prints 37, which is the expected result. But when I compile using -O3
, the code prints 0.
The platform is Ubuntu 20.04, with GCC 9.3.0
Can anyone helps me understand the behavior?
builder.h
class Builder {
public:
template<typename C>
static C build() {
return 0;
}
};
builder.cc
#include "builder.h"
template<>
int Builder::build<int>() {
return 37;
}
main.cc
#include "builder.h"
#include <iostream>
int main() {
std::cout << Builder::build<int>() << '
';
}
makefile
CXX_FLAG = -O0 -g
all:
g++ $(CXX_FLAG) builder.cc -c -o builder.o
g++ $(CXX_FLAG) main.cc builder.o -o main
clean:
rm *.o
rm main
question from:https://stackoverflow.com/questions/65876360/c-template-specialization-causes-different-result-in-debug-release