我正在嘗試創建自定義容器,并將它們用作模板類中的回傳型別。我不得不使用 C 98,所以想知道如何編譯以下代碼:
#include <string>
#include <vector>
/// Make a container called Vector<T>
template<typename T>
struct Vector
{
typedef std::vector<T> type;
};
/// Some ordinary class that holds that data.
class Data
{
public:
Data();
template<typename T>
typename Vector<T>::type* getVec();
/// Specialization
template<>
typename Vector<int>::type* getVec();
};
來自編譯器的錯誤是:
error: no function template matches function template specialization 'getVec'
為什么 getVec() 的“int”專業化不起作用?
uj5u.com熱心網友回復:
C 98 關于特化位置的規則比現代 C 的直觀性稍差一些。
可以這么說,您需要將專業化放在命名空間范圍內
/// Specialization - declare after the class
template<>
Vector<int>::type* Data::getVec<int>();
除此之外,您必須明確指定<int>引數,因為它在函式宣告中不可推導。我還洗掉了多余的typename(我們現在處于具有具體型別的背景關系中)。
uj5u.com熱心網友回復:
你可能會
/// Some ordinary class that holds that data.
class Data
{
public:
Data();
template<typename T>
typename Vector<T>::type* getVec();
};
/// Specialization
template<>
Vector<int>::type* Data::getVec<int>()
{
return NULL;
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/372512.html
上一篇:如何正確讓用戶在第一個輸出中輸入等級并顯示第二個輸出基數?
下一篇:在C 中嵌套成員函式時遇到問題
