c++ - 可变参数模板迭代和 GCC

标签 c++ qt gcc variadic-templates

我已经根据 wiki 实现了可变参数模板函数。并在“使用函数的“终止版本”重载”的帮助下迭代它。代码:

void writeValue(QDataStream& /*data*/) {}

template<typename A, typename... Values>
void writeValue(QDataStream& data, const A& arg1, const Values&... args)
{
    data << arg1;
    writeValue(data, args...);
}

template<typename... Values>
quint32 PrepareMessage(QDataStream& data, func_code fcode, Values... parameters)
{
  data << quint32(fcode);
  writeValue(data, parameters...);
  return 0;
}

它可以通过 MSVC2013 64 位工具链与 Qt 5.5 for Windows 一起构建和使用,不会出现任何问题。 现在,我尝试使用 Qt 5.5 for Linux over GCC 64 位在 Linux 上构建相同的代码,但在编译时出现以下错误:

g++ -c -pipe -std=c++11 -g -Wall -W -D_REENTRANT -fPIC -D_64bit -DQT_NETWORK_LIB -DQT_CORE_LIB -I../Trans2QuikWrapper -I. -I../../../Qt/5.5/gcc_64/include -I../../../Qt/5.5/gcc_64/include/QtNetwork -I../../../Qt/5.5/gcc_64/include/QtCore -I. -I../../../Qt/5.5/gcc_64/mkspecs/linux-g++ -o moc_T2Q_Client.o moc_T2Q_Client.cpp
g++ -Wl,-rpath,/home/truf/Qt/5.5/gcc_64 -Wl,-rpath,/home/truf/Qt/5.5/gcc_64/lib -o t2q T2Q_Client.o main_client.o moc_T2Q_Client.o   -L/home/truf/Qt/5.5/gcc_64/lib -lQt5Network -lQt5Core -lpthread 
main_client.o: In function `int QGenericAtomicOps<QBasicAtomicOps<4> >::load<int>(int const&)':
/home/truf/.wine/drive_c/build-t2q-Desktop_Qt_5_5_1_GCC_64bit-Debug/../Trans2QuikWrapper/io_utils.h:16: multiple definition of `writeValue(QDataStream&)'
Makefile:192: recipe for target 't2q' failed
T2Q_Client.o:/home/truf/.wine/drive_c/build-t2q-Desktop_Qt_5_5_1_GCC_64bit-Debug/../Trans2QuikWrapper/io_utils.h:16: first defined here
moc_T2Q_Client.o: In function `int QGenericAtomicOps<QBasicAtomicOps<4> >::load<int>(int const&)':
/home/truf/.wine/drive_c/build-t2q-Desktop_Qt_5_5_1_GCC_64bit-Debug/../Trans2QuikWrapper/io_utils.h:16: multiple definition of `writeValue(QDataStream&)'
T2Q_Client.o:/home/truf/.wine/drive_c/build-t2q-Desktop_Qt_5_5_1_GCC_64bit-Debug/../Trans2QuikWrapper/io_utils.h:16: first defined here
collect2: error: ld returned 1 exit status
make: *** [t2q] Error 1

gcc版本是5.2.1 20151010(Ubuntu 5.2.1-22ubuntu2)。不涉及 Wine - 只是一个文件夹位置。

那里支持可变参数模板吗?需要额外的编译参数吗?或者问题出在代码中?

最佳答案

错误消息显示:

multiple definition of `writeValue(QDataStream&)'

要解决此问题,您必须将 writeValue() 声明为 inline:

inline void writeValue(QDataStream& /*data*/) {}

当您在头文件中定义函数时,您始终应该将其标记为内联。这样,就不会破坏 ODR如果您在多个翻译单元中包含 header 。

关于c++ - 可变参数模板迭代和 GCC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33914266/

相关文章:

c++ - 为什么 *this 可以用作 & 类型?

c++ - 我无法在 QT 中编译我的项目

c - GCC-4.3.2 中提供的标准算法

c++ - 你能给我一些 C++ 中奇怪的单行注释的例子吗?

c++ - 调用非静态函数作为谓词?

c++ - 使用 Valgrind 抑制 Qt 内存泄漏的文件

c++ - 如何选择 libc6 或 libc6-dbg

c++ - 如何使用初始化列表构造函数以外的东西为类成员设置默认值

c++ - 处理 C++ "initialized but not referenced"警告以销毁作用域助手?

android - QAbstractButton 和 QPushButton* 之间的比较缺少强制转换