我想調用template<typename T> foo(T x)
並手動處理這些情況:T = std::vector<U>
,T = std::string
,T =
任何其他情況。模板專業化問題
這裏是我寫爲:
#include <iostream>
#include <vector>
#include <string>
template<typename T> void foo_impl(const std::string &data, std::string *) {
std::cout << "foo for std::string called\n";
}
template<typename T> void foo_impl(const T &data, T *) {
std::cout << "foo for general types called\n";
}
template<typename T> void foo_impl(const std::vector<T> &data, std::vector<T> *) {
std::cout << "foo for std::vector<T> called\n";
}
template<typename T> void foo(const T &data) {
foo_impl(data, static_cast<T*>(nullptr));
}
int main() {
int i = 1;
foo(i);
std::vector<int> a = {0, 1};
foo(a);
std::string s = "abcd";
foo<std::string>(s);
return 0;
}
然而,foo(std::string x)
被稱爲萬一「T
是任何其他類型的」。我如何處理它?
注意,'的std :: VECTOR'有不止一個模板參數。 –
作爲第二個參數的虛擬指針的作用是什麼?你的類型是從第一個參數中推導出來的。 – SergeyA
@SergeyA真的嗎?怎麼樣std :: vector? –
omtcyfz