2015-06-09 79 views
1
#include <iostream> 
#include <string> 
using namespace std; 

template <class Type> 
class Matrix 
{ 
public: 
    Type matrix[2][2]; 

     for (int i = 0; i < 2; i++) { 
      for (int j = 0; j < 2; j++) { 
       if (typeid(matrix[0][0]).name() == typeid(string).name()) { 
        matrix[i][j] = "0"; 
       } 
       else { 
        matrix[i][j] = 0;  //this is where I get C2593 
       } 
      } 
     } 
    } 
}; 

int main() 
{ 
    Matrix<string> mString; 
    Matrix<int> mInt; 
    . 
    . 
    . 
    return 0; 
} 

所以,我在此基質模板,我想"0"初始化它,如果矩陣的類型爲字符串。否則,我想用0進行初始化。我在這裏嘗試了這件事,我得到了一個error C2593: 'operator =' is ambiguous。有什麼我可以做的,或者我的方法是完全錯誤的?不同的構造函數模板:一個字符串和一個爲別的

+0

[模板專業化](http://www.cprogramming.com/tutorial/template_specialization.html)? –

+0

另外,如果字符串矩陣在初始化時真的應該是字符串「0」,而不僅僅是空的?因爲那樣你就可以'矩陣[i] [j] = T();' –

+0

哦,我在拼寫時犯了一個錯誤。我不是故意放置括號。 @JoachimPileborg不幸的是,他們必須,是的。 –

回答

4

它最終取決於Matrixintstring之間有多少不同。

如果你正在處理的是最初的默認值,最簡單的解決辦法可能是外包給一個輔助函數:

template <class Type> 
class Matrix 
{ 
    Matrix() { 
     for (int i = 0; i < 2; i++) { 
      for (int j = 0; j < 2; j++) { 
       setDefault(matrix[i][j]); 
      } 
     } 
    } 

    // ... 

    template <typename U> 
    void setDefault(U& u) { u = 0; } 

    void setDefault(std::string& u) { u = "0"; } 
}; 

如果你正在做的事情比較複雜,那麼你可能要明確專門:

template <> 
class Matrix<std::string> { 
    // Matrix of strings 
}; 
+0

你好,先生,是一名專業人士。非常感謝,我從來沒有想過這個輔助功能的東西!它像一個魅力 –

相關問題