我需要能夠對模板的任何專業的存儲在一個變量如:C++變量保存類模板的任何專業的
template<T>
class Grid {
int GetRows();
int GetTypeOfColumn(int col);
//...etc...
}
//EDIT:
Grid<int>::GetTypeofColumn(int col) {
return col == 0 ? STRING_COL_TYPE : INT_COL_TYPE;
}
Grid<string>::GetTypeofColumn(int col) {
return STRING_COL_TYPE;
}
//End EDIT
class Foo {
Grid<int>* aBunchOfNumbers;
Grid<string>* aBunchOfStrings;
//...etc...
}
//in some function, say `wants` is an enum, and foo is gotten from somewhere:
Foo* foo;
switch wants {
case NUMBERS:
std::cout << "Rows: " << foo->aBunchOfNumbers->GetRows() << std::endl;
std::cout << "Col0 is: " << foo->aBunchOfNumbers->GetTypeofColumn(0) << std::endl;
//...etc...
break;
case STRINGS:
std::cout << "Rows: " << foo->aBunchOfNumbers->GetRows() << std::endl;
std::cout << "Col0 is: " << foo->aBunchOfNumbers->GetTypeofColumn(0) << std::endl;
//...etc...
break;
}
它會更容易做到:
Foo* foo;
Grid* grid;
switch wants {
case NUMBERS:
grid = foo->aBunchOfNumbers;
break;
case STRINGS:
grid = foo->aBunchOfStrings;
break;
}
std::cout << "Rows: " << grid->GetRows() << std::endl;
std::cout << "Col0 is: " << grid->GetTypeofColumn(0) << std::endl;
//...etc...
以同樣的方式,如果我使用這樣的子類:http://ideone.com/MPKy1w
我知道類模板幾乎基本上是宏和編譯器如何實際編譯它們,但是沒有一般參考專業化並保存重複的方法?
(我用三分球故意在這裏,我有我的實際代碼沒有選擇,我不能在這裏複製)
你想要一些多態性。有靜態(重載,模板)和動態(虛擬功能)。只需選擇一個。 –
但是,多態性,他不需要爲他想包含的每個新類定義派生類嗎? – Stephen
@Stephen不包含模板 – jaggedSpire