简体   繁体   中英

variadic template function overloading failes

I am trying to implement some kind of StringBuilder for some unit tests. The problem is that I am heavily using QByteArray within some templates, which is using the StringBuilder for logging. In order to use QByteArray in an QString().arg() I usually have to wrap the byte array with QString(...) .

So I tried the following:

const char* buildCString(const QString& msg ){
    return msg.toLatin1().toStdString().data();
}

template<typename Head, typename ...Tail>
const char* buildCString(const QString& msg, const Head& arg, const Tail&... rest){
    return buildCString(msg.arg(arg), rest...); //generic use case 
}

template<typename Head, typename ...Tail>
 const char* buildCString(const QString& msg, const QByteArray& arg, const Tail&... rest){
    return buildCString(msg.arg(QString(arg)), rest...); 
}

void main(){
    auto data = buildCString("double %1, QByteArray %2, int %3", 0.123, QByteArray("Test"), 2);
    cout << "Data: " << data << endl;
}

And receive the following error:

In instantiation of 'const char* buildCString(QString, Head, Tail ...) [with Head = QByteArray; Tail = {int}]':
required from 'const char* buildCString(QString, Head, Tail ...) [with Head = double; Tail = {QByteArray, int}]'
required from here
Fehler: call of overloaded 'arg(QByteArray&)' is ambiguous
     return buildCString(msg.arg(arg), rest...);

So the generic function gets called instead of the more specialized one.

My question is why doesn't the overloading kick in? I have the feeling I am missing something basic here but after searching serveral hours for an solution I still can't wrap my head around it.

I am using Qt 5.9.0 and mingw32 5.3.0 32Bit.

In this overload...

template<typename Head, typename ...Tail>
 const char* buildCString(const QString& msg, const QByteArray& arg, const Tail&... rest){
    return buildCString(msg.arg(QString(arg)), rest...); 
}

...the template parameter Head can never be deduced. You should get rid of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM