Skip to content

Instantly share code, notes, and snippets.

@diosmosis
Created February 19, 2012 11:49
Show Gist options
  • Save diosmosis/1863408 to your computer and use it in GitHub Desktop.
Save diosmosis/1863408 to your computer and use it in GitHub Desktop.
charmed examples
#include <iostream>
#include <string>
#include <boost/foreach.hpp>
#include <charmed/charmed.hpp>
// the attribute
struct operation_attribute
{
operation_attribute(std::string const& name_, std::string const& help_)
: name(name_), help(help_)
{}
std::string name;
std::string help;
};
// tell charmed to index operation_attributes by their name
namespace charmed
{
template <>
struct index_specifier_of<operation_attribute>
{
typedef boost::multi_index::indexed_by<
boost::multi_index::sequenced,
boost::multi_index::ordered_unique<
boost::multi_index::member<
operation_attribute,
std::string,
&operation_attribute::name
>
>
> type;
};
}
// the operations
typedef void (operation_type)(int, char**);
void operation1(int argc, char ** argv)
{
std::cout << "IN operation1" << std::endl;
}
CHARMED_TAG_FUNCTION(
&operation1, operation_attribute("operation1", "This is the first operation."));
void operation2(int argc, char ** argv)
{
std::cout << "IN operation2" << std::endl;
}
CHARMED_TAG_FUNCTION(
&operation2, operation_attribute("operation2", "This is the second operation."));
void help(int argc, char ** argv)
{
std::cout << "Available operations are:\n" << std::endl;
BOOST_FOREACH(operation_attribute const& oa,
charmed::all_attributes<operation_attribute, 1>())
{
std::cout << oa.name << " - " << oa.help << std::endl;
}
}
CHARMED_TAG_FUNCTION(&help, operation_attribute("help", "Displays this message."));
int main(int argc, char ** argv)
{
// for brevity, assume the args are correct
std::string op_name(argv[1]);
// find the op by name & invoke it
operation_attribute const* oa =
charmed::find_attribute<operation_attribute, 1>(op_name);
if (!oa)
{
std::cout << "Don't know what the '" << op_name << "' operation is..."
<< std::endl;
return EXIT_FAILURE;
}
charmed::tagged_type_of<operation_type>(*oa)(argc, argv);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment