Skip to content

Instantly share code, notes, and snippets.

@lambday
Last active August 29, 2015 14:20
Show Gist options
  • Select an option

  • Save lambday/21618e6bac4898dd2149 to your computer and use it in GitHub Desktop.

Select an option

Save lambday/21618e6bac4898dd2149 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <cstdio>
#include <string>
#include <functional>
#include <cmath>
#include <initializer_list>
/*
Format("{type} {name} = -2*{pi}*sqrt(element)*pow({weights},2)",
Parameter("type") = data_type,
Parameter("name") = "outer_factor",
Parameter("pi") = pi,
Parameter("weights") = 0.6);
output = float outer_factor=-2*3.1415+sqrt(element)*pow(0.6, 2);
*/
struct Parameter {
Parameter(const char* name) : m_name(name) {}
template <typename T>
Parameter& operator=(const T& value) {
cast = [&value]() { return std::to_string(value); };
return *this;
}
Parameter& operator=(const char* value) {
cast = [&value]() { return std::string(value); };
return *this;
}
Parameter& operator=(std::string value) {
cast = [&value]() { return value; };
return *this;
}
operator std::string() const {
return cast();
}
std::function <std::string()> cast;
std::string m_name;
};
// ripped from http://stackoverflow.com/questions/2896600/how-to-replace-all-occurrences-of-a-character-in-string
std::string replace_all(std::string str, const std::string& from, const std::string& to) {
size_t start_pos = 0;
while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
return str;
}
std::string format(const char* str, std::initializer_list<Parameter> params) {
std::string fmt(str);
std::cout << fmt << std::endl;
for (auto i = params.begin(); i != params.end(); ++i) {
fmt = replace_all(fmt, "{" + i->m_name + "}", *i);
}
return fmt;
}
int main() {
float weights = 0.6;
std::string s = Parameter("weights") = weights;
std::cout << s << std::endl;
s = Parameter("pi") = M_PI;
std::cout << s << std::endl;
s = Parameter("type") = "float";
std::cout << s << std::endl;
const char name[] = "double";
s = Parameter("type") = name;
std::cout << s << std::endl;
std::string name_s("int");
s = Parameter("type") = name_s;
std::cout << s << std::endl;
s = Parameter("val") = 1024;
std::cout << s << std::endl;
std::string fmt = format("{type1} {name_2} = -2*{pi_m}*sqrt(element)*pow({weights},2);",
{
Parameter("type1") = "float",
Parameter("name_2") = "outer_factor",
Parameter("pi_m") = M_PI,
Parameter("weights") = weights
} );
std::cout << fmt << std::endl;
return 0;
}
Success time: 0 memory: 3236 signal:0
0.600000
3.141593
float
double
int
1024
{type1} {name_2} = -2*{pi_m}*sqrt(element)*pow({weights},2);
float outer_factor = -2*3.141593*sqrt(element)*pow(0.600000,2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment