Variadic 模板迭代和 GCC

Variadic template iteration and GCC

我已经根据 wiki 实现了可变模板函数。并在"overloading with "终止版本“函数”的帮助下对其进行迭代。代码:

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;
}

它可以在 Qt 5.5 for Windows over MSVC2013 64bit 工具链上毫无问题地构建和使用。 现在,我正在尝试在 Linux 上使用 Qt 5.5 为 Linux 在 GCC 64 位上构建相同的代码,并在编译时出现以下错误:

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*/) {}

当您在 header 文件中 定义 函数时,您 总是应该 将其标记为 inline .这样,如果您在多个翻译单元中 include header,它就不会破坏 ODR