2016-03-06 136 views
2

我遇到了模板问题,我想获取文件的内容并将其存储在字符串中。我正在使用Qt来处理char *,QString和字符串。模板函数C++,采用参数U并返回T

我有一个模板,我与拨打:

std::string test = openStyle("style.css"); 

我想在测试styleToAdd,这是我的文件的style.css的内容来获得:

编辑:更改常量T & openstyle to const T,感谢球场。

template<typename T> 
const T openStyle(const T &type) 
{ 
    QFile File(QCoreApplication::applicationDirPath() + "/" + type); 
    File.open(QFile::ReadOnly); 
    QString styleToAdd = QLatin1String(File.readAll()); 

    return (styleToAdd); 
} 

但编译说:

invalid initialisation of reference type "const char (&)[14]" from expression "QString" 

我认为这是因为在模板,返回值是一样的参数,而不是我测试变量,但有没有办法能够返回另一个类型(在通用的方式)

,所以我们可以做这样的事情与模板:

std::string test = openStyle("style.css"); 
char * test = openStyle("style.css"); 
QString test = openStyle("style.css"); 
const char * test = openStyle("style.css"); 
+6

你为什么在以下情况下需要使用模板函数:它的参数是一个文件名,它总是一个字符串;你总是希望它返回一个字符串。这里不需要模板功能。正如俗话所说:“你越想过管道,就越容易堵塞排水沟。” –

+0

如果您可以使用C++ 14,请尝试使用自动返回类型演绎。 – chrizke

回答

1

以您尝试的方式自动确定函数的返回类型是不可能的。

如果你想为你描述的模板函数,语法是这样的:

template<typename T, typename U> 
const T &openStyle(const U &type) 

,但你需要调用它像这样:

std::string test = openStyle<std::string,const char[]>("style.css"); 

这可能不是什么你要。除此之外,你将不得不找到一种方法来将你的QString styleToAdd转换为任何类型的T - 所以问题没有解决,但只是移动到返回类型。

由于文件名始终是一个字符串,你可以简单地选择一个在这儿,总是返回QString并定义你这样的功能:

const QString &openStyle(const std::string &type) 
//choose if you like std::string, QString or char[] here. 

虽然你不能重载转换运算符的QString之外,你使用所提供的功能和QString::toStdString()std::string::c_str()

operator<< (std::string& left,const QString& right){left = right.toStdString();} 
operator<< (char*, const QString&); //similar conversions here 
operator<< (QString&, const std::string&); //and here 

然后写:能全局重载流操作者所需要的类型

std::string test << openStyle("style.css"); 
char * test << openStyle("style.css"); 
QString test << openStyle("style.css"); 
const char * test << openStyle("style.css"); 
1

您不需要此模板。如果type是任何不是字符串或不能隐式转换为一个字符串,您的代码将失败。

我看你想从这个拿到例子,我能告诉你的是,

  • QStringtoStdString()toUtf8()等功能,其返回std::string相当于你QString对象的
  • std::string可以使用c_str()函数转换为C字符串。

此外,您还可以使用QByteArray的结果从QString::toLatin1()存储,然后调用QByteArray::data()并将其分配给一个const char *转换QString为C-字符串。这是最重要的omho,但它是另一种做事方式。

如果您不想每次要将QString转换为两个标准C/C++字符串表示形式之一时不想执行所有步骤和调用,则可以创建小函数。

1

考虑到您使用的是QT,您可能会考虑只使用QString类,并最终在要将其转换为const char *或std :: string对象时调用QString的方法。你并不真的需要这个模板。你可以使用类似的东西:

QString openStyle(const QString &type) { ... } 

也有一个真正讨厌的错误到你的代码:你想一个常量引用返回给一个局部变量,这是错误的,并会导致未定义行为(很可能你会得到一个核心转储)。 正如你所看到的,我已经改变了从常量牛逼&您的返回类型T.

2

你可以用C++编译14,用他的自动复原型抵扣-std=c++1y

template<typename T> 
auto T openStyle(const T &type) 
{ 
    QFile File(QCoreApplication::applicationDirPath() + "/" + type); 
    File.open(QFile::ReadOnly); 
    QString styleToAdd = QLatin1String(File.readAll()); 

    return (styleToAdd); 
}