2016-03-06 91 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); 
}