QList带有模板的通用join()函数 [英] QList generic join() function with template

查看:141
本文介绍了QList带有模板的通用join()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为QList创建通用的join()函数(如QStringList的join()),以便为任何类型的QList创建toString()函数.此函数带有一个QList,一个分隔符和一个确定如何打印项目的函数.考虑以下代码:

I am trying to make a generic join() function for QList (like join() for QStringList) in order to make a toString() function for a QList of any type. This function takes a QList, a separator and a function to dertermine how to print items. Consider this code :

#include <QList>
#include <QDebug>

template <class T>
static QString join(const QList<T> &list, const QString &separator, const std::function< QString (const T &item) > toStringFunction)
{
    QString out;
    for(int i = 0; i<list.size(); i++)
        out+= (i ? separator : "") + toStringFunction(list[i]);
    return out;
}

int main(int argc, char *argv[])
{
    QList <double> list;
    list<<1.<<2.<<3.<<4.;
    int precision = 1;
    QString out = join(list, ",",[precision](const double &item)->QString{
                    return QString::number(item,'f',precision);
                    });

    qDebug()<<out;
    return 1;
}

这是我遇到的错误:

src\main.cpp(18): error C2672: 'join': no matching overloaded function found
src\main.cpp(20): error C2784: 'QString join(const QList<T> &,const QString &,const std::function<QString(const T &)>)': could not deduce template argument for 'const std::function<QString(const T &)>' from 'main::<lambda_f1fd4bbd6b8532d33a84751b7c214924>'
src\main.cpp(5): note: see declaration of 'join'

很明显,我并不关心此功能,有很多解决方案可以做到这一点.但是我不明白我在这里用模板做错了什么.

Clearly I dont care about this function, plenty of solutions to do it. But I don't understand what I am doing wrong with templates here.

无法推断出模板参数???

could not deduce template argument ???

NB:

out = join<double>(list, ",",[precision](const double &item)->QString{
    return QString::number(item,'f',precision);
}); 

=>工作正常

const std::function<QString(const double &item)> toStringFunction = [precision](const double &item)->QString{
    return QString::number(item,'f',precision);
};
out = join(list, ",",toStringFunction);

=>工作正常

推荐答案

我不确定C ++内部情况如何,但是它确实适用于以下声明:

I'm not sure what's going on with the C++ internals, but it does work with this declaration:

template <class T> 
static QString join(const QList<T> &list, 
                    const QString &separator, 
                    const std::function< QString (const typename QList<T>::value_type &) > toStringFunction)

我认为 QList 可以从正在传递的 list 中确定模板类型,而 join 模板本身无法确定.

I think QList can determine the template type from the list being passed, while the join template itself can't.

这篇关于QList带有模板的通用join()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆