Incorrect (?) template specialization results when compiling with -O3

Adam McLaurin gcc@irotas.net
Fri Jul 10 15:18:00 GMT 2009


Consider the following code:

// Binky.h
#ifndef BINKY_H
#define BINKY_H
template<typename T> const char* getString()
{
    return "T";
}
#endif

// Binky.cpp
#include "Binky.h"
template<> const char* getString<int>()
{
    return "int";
}

// test.cpp
#include "Binky.h"
#include <cstdio>
int main(int argc, char** argv)
{
    printf("getString<double>(): %s\n", getString<double>());
    printf("getString<int>():    %s\n", getString<int>());
    return 0;
}


If I compile with anything other than -O3, I get:
getString<double>(): T
getString<int>():    int

However, with -O3 I get:
-$ ./functemp                             
getString<double>(): T
getString<int>():    T


This is rather unexpected! 

I see this in g++ 4.2.4, 3.3.6, and 3.2.2.

Is this a GCC bug? If not, what can I do differently to produce
consistent results regardless of optimizations?

Thanks,
Adam



More information about the Gcc-help mailing list