cpp_playground/misc/template.cpp

49 lines
1.1 KiB
C++
Raw Permalink Normal View History

2023-08-28 23:52:31 +08:00
#include <assert.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int32_t getInt() {
return INT32_MAX;
}
int64_t getInt64() {
return INT64_MAX;
}
void getStr(string& str) {
str = "abc";
}
void getVInt(vector<int>& vint) {
vint = {1, 2, 3};
}
void getVStr(vector<string>& vstr) {
vstr = {"abc", "def"};
}
template <typename T>
T getVal() {
T val;
T& rVal = val;
if (typeid(T) == typeid(int)) {
(int&)rVal = getInt();
} else if (typeid(T) == typeid(int64_t)) {
(int64_t&)rVal = getInt64();
} else if (typeid(T) == typeid(string)) {
getStr((string&)rVal);
} else if (typeid(T) == typeid(vector<int>)) {
getVInt((vector<int>&)rVal);
} else if (typeid(T) == typeid(vector<string>)) {
getVStr((vector<string>&)rVal);
}
return val;
}
int main() {
assert(getVal<int32_t>() == INT32_MAX);
assert(getVal<int64_t>() == INT64_MAX);
assert(getVal<string>() == "abc");
assert(getVal<vector<int>>() == vector<int>({1, 2, 3}));
assert(getVal<vector<string>>() == vector<string>({"abc", "def"}));
}