可變索引模板
某些情況下,我們需要指定參數的索引並輸出,此時可以選擇可變索引模板,只要支持[]
操作的,都可以執行可變索引模板。下面給出代碼實例:
#include <iostream>
#include <vector>
#include <string>
#include <map>
template<typename T, typename... Args>
void Print(T&& val, Args&&... args) {
std::cout << val << " ";
if constexpr (sizeof...(args) > 0) {
Print(args...);
}
}
template<typename Con, typename... Idx>
void PrintConElem(const Con&& con, const Idx&&... idx) {
Print(con[idx]...); // 對Idx展開
}
int main() {
std::vector<int> vec{0, 1, 2, 3, 4, 5};
std::vector<std::string> vecStr{"0", "1", "2", "3", "4", "5"};
double vecd[6]{0.0, 1.0, 2.0, 3.0, 4.0, 5.0};
std::map<std::string, std::string> mp{{"0", "mp0"}, {"1", "mp1"},
{"2", "mp2"}, {"3", "mp3"},
{"4", "mp4"}, {"5", "mp5"}};
Print(vec[1], vec[3], vec[5]);
Print(vecStr[0], vecStr[2], vecStr[4]);
Print(vecd[1], vecd[3], vecd[5]);
Print(mp["0"], mp["2"], mp["4"]);
return 0;
}
template template
當模板參數本身還要依賴其它模板時,可以引入template template的方式,理解爲可變參數模板。舉個例子,假設我們需要哈希表,此時需要指定key
和value
的類型;同時,我們需要指定存儲它們的容器,容器本身也是泛型,此時就需要template template技術。
代碼實例:
#include <iostream>
#include <deque>
template <typename T>
class MyContainer {
public:
void push(T&& arg) {
m_que.emplace_back(std::forward<T>(arg));
}
T pop() {
auto&& v = m_que.front();
m_que.pop_front();
return v;
}
private:
std::deque<T> m_que;
};
// class是類的意思
template <typename Key, typename Value, template<typename T> class Container>
class MyHashTable {
public:
void push(Key&& key, Value&& value) {
// TODO:
}
Value pop(Key&& key) {
// TODO:
}
bool exist(Key&& key) {
// TODO:
return true;
}
private:
Container<Key> m_Keys;
Container<Value> m_Values;
};
int main() {
return 0;
}