Skip to content

Instantly share code, notes, and snippets.

@Mytherin
Created June 8, 2020 15:33
Show Gist options
  • Save Mytherin/a531482de79038725d9b655727c74b5f to your computer and use it in GitHub Desktop.
Save Mytherin/a531482de79038725d9b655727c74b5f to your computer and use it in GitHub Desktop.
Variadic templates to find types
#include <string>
#include <vector>
#include <iostream>
#include <type_traits>
using namespace std;
template<typename T>
string GetArgumentType() {
if (std::is_same<T, int>()) {
return "INT";
} else if (std::is_same<T, double>()) {
return "DOUBLE";
} else {
// unrecognized type
throw std::exception();
}
}
template <typename TA>
void GetArgumentTypesRecursive(vector<string> &arguments) {
arguments.push_back(GetArgumentType<TA>());
}
template<typename TA, typename TB, typename... Args>
void GetArgumentTypesRecursive(vector<string> &arguments) {
arguments.push_back(GetArgumentType<TA>());
GetArgumentTypesRecursive<TB, Args...>(arguments);
}
template<typename TA, typename... Args>
void PrintTypes(string function_name) {
vector<string> arguments;
GetArgumentTypesRecursive<TA, Args...>(arguments);
if (arguments.size() < 1) {
cout << "at least one template (return type) is required!\n";
throw std::exception();
}
// first one is return type
cout << function_name << "(";
for(int i = 1; i < arguments.size(); i++) {
if (i > 1) {
cout << ", ";
}
cout << arguments[i];
}
cout << ") -> " << arguments[0] << "\n";
}
int main() {
// first param is return type:
// udf() -> INT
PrintTypes<int>("udf");
// udf(DOUBLE, DOUBLE) -> INT
PrintTypes<int, double, double>("udf");
// udf(INT, DOUBLE, INT) -> INT
PrintTypes<int, int, double, int>("udf");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment