gpt4 book ai didi

c++ - GCC 向依赖默认构造函数的模板化类中的静态数据成员给出 "undefined reference"错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:02:06 24 4
gpt4 key购买 nike

我遇到了类似的问题:

"undefined reference" to static field template specialization

但他们使用的解决方法对我不起作用。

我有一个带有静态数据成员的 CRTP 类,其中之一是 std::mutex。不幸的是,GCC (4.8.2) 的链接器给我这个互斥锁的“ undefined reference ”错误。 Clang (3.4) 没有。有解决方法吗?最初的问题(上面链接)在静态数据成员上调用了复制构造函数,迫使 GCC 发出一个符号,但是由于我的数据成员是 std::mutex,所以这不是一个选项——复制构造函数被删除,并且有没有参数构造函数。我只是被冲洗了吗?

我认为问题不在于 std::mutex,我认为问题在于 GCC 如何处理依赖于默认构造函数的模板类中的静态数据成员。

感谢您的帮助!

这是我的问题的精简版:测试.hh

#include <mutex>

template < class T >
class CRTP_class {
public:
T * ptr_;
static std::mutex mutex_; // linker error here
static int clearly_a_problem_with_mutex_; // no linker error here
};

class Foo : public CRTP_class< Foo >
{
public:
void set_bar( int setting );
int bar_;
};

测试.cc

#include <test.hh>

template<> std::mutex CRTP_class< Foo >::mutex_;
template<> int CRTP_class< Foo >::clearly_a_problem_with_mutex_( 0 );

void Foo::set_bar( int setting ) {
std::lock_guard< std::mutex > locker( mutex_ );
++clearly_a_problem_with_mutex_;
bar_ = setting;
}

主.cc

#include <test.hh>

int main() {
Foo foo;
foo.set_bar( 5 );
}

然后我用这个命令编译:

g++ -std=c++0x main.cc test.cc -I.

得到错误

/tmp/cclyxUfC.o: In function `Foo::set_bar(int)':
test.cc:(.text+0x86): undefined reference to `CRTP_class<Foo>::mutex_'
collect2: error: ld returned 1 exit status

(编辑 1:针对建议这是一个重复错误的评论者,“为什么模板必须在头文件中”——将单独的模板特化放入 .cc 文件并没有什么奇怪的到 .hh 文件中——当你有一个 mutex 并且出于显而易见的原因,你只需要该互斥体的一个拷贝时,这正是你所需要的。如果你声明一个头文件中的静态数据成员,那么每个#includes 头文件的翻译单元将以它们自己的互斥锁拷贝结束,在这种情况下,它没有服务于确保互斥的工作)

(编辑 2:糟糕!我链接到错误的先前错误。)

最佳答案

来自 Bugzilla 上 GCC 的 Jonathan Wakely:

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63876

问题似乎是我没有为互斥体提供初始化程序。其语法是提供一个打开和关闭的花括号

template<> std::mutex CRTP_class< Foo >::mutex_;

成为

template<> std::mutex CRTP_class< Foo >::mutex_{};

(将互斥量存在于 .cc 文件中没有问题)

关于c++ - GCC 向依赖默认构造函数的模板化类中的静态数据成员给出 "undefined reference"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26935824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com