mercredi 25 octobre 2017

C++ error only when compiled with no optimizations (GCC)

Here is some code:

#include<iostream>

using namespace std;

class ShowHello {
 public:
    string operator()(int x) {return "hello";}
};

template<typename F>
class A {
 private:
    static F f;
    static inline string foo(const int& x) {
        return f(x);
    }

 public:
    A() {
        cout << "foo: " << foo(10) << endl;
    }
};


int main(int argc, char *argv[])
{
    A<ShowHello> a;
    return 0;
}

And here is me compiling it with some optimizations:

$ g++ -std=c++11 -O1 -Wall test.cc -o test && ./test
foo: hello

And no optimizations

$ g++ -std=c++11 -O0 -Wall test.cc -o test && ./test
/tmp/ccXdtXVe.o: In function `A<ShowHello>::foo(int const&)':
test.cc:(.text._ZN1AI9ShowHelloE3fooERKi[_ZN1AI9ShowHelloE3fooERKi]+0x2a): undefined reference to `A<ShowHello>::f'
collect2: error: ld returned 1 exit status

What am I doing wrong?

Also

$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Aucun commentaire:

Enregistrer un commentaire