【发布时间】:2018-04-06 17:05:46
【问题描述】:
这是一些代码:
#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;
}
这里是我用一些优化编译它:
$ g++ -std=c++11 -O1 -Wall test.cc -o test && ./test
foo: hello
没有优化
$ 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
我做错了什么?
还有
$ 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.
【问题讨论】:
-
你声明静态成员变量
f,但你从来没有定义它。在优化的构建中,它可能已经优化了,因为它没有被使用。