Allow getting option values providing a template type

This commit is contained in:
Matias Fontanini
2016-06-20 20:07:10 -07:00
parent 0a58fc306b
commit bba9043faf
6 changed files with 70 additions and 0 deletions

View File

@@ -75,6 +75,7 @@ public:
using SocketCallback = std::function<int(int domain, int type, int protoco)>;
using ConfigurationBase<Configuration>::set;
using ConfigurationBase<Configuration>::get;
/**
* Default constructs a Configuration object

View File

@@ -32,11 +32,15 @@
#include <string>
#include <map>
#include "exceptions.h"
namespace cppkafka {
template <typename Concrete>
class ConfigurationBase {
private:
template <typename T>
struct Type2Type { };
public:
/**
* Sets a bool value
@@ -60,6 +64,25 @@ public:
void set(const std::string& name, const char* value) {
proxy_set(name, value);
}
/**
* \brief Gets a value, converting it to the given type.
*
* If the configuration option is not found, then ConfigOptionNotFound is thrown.
*
* If the configuration value can't be converted to the given type, then
* InvalidConfigOptionType is thrown.
*
* Valid conversion types:
* * std::string
* * bool
* * int
*/
template <typename T>
T get(const std::string& name) const {
std::string value = static_cast<const Concrete&>(*this).get(name);
return convert(value, Type2Type<T>());
}
protected:
static std::map<std::string, std::string> parse_dump(const char** values, size_t count) {
std::map<std::string, std::string> output;
@@ -72,6 +95,31 @@ private:
void proxy_set(const std::string& name, const std::string& value) {
static_cast<Concrete&>(*this).set(name, value);
}
static std::string convert(const std::string& value, Type2Type<std::string>) {
return value;
}
static bool convert(const std::string& value, Type2Type<bool>) {
if (value == "true") {
return true;
}
else if (value == "false") {
return false;
}
else {
throw InvalidConfigOptionType(value, "bool");
}
}
static int convert(const std::string& value, Type2Type<int>) {
try {
return std::stoi(value);
}
catch (std::exception&) {
throw InvalidConfigOptionType(value, "int");
}
}
};
} // cppkafka

View File

@@ -65,6 +65,14 @@ public:
ConfigOptionNotFound(const std::string& config_name);
};
/**
* Indicates a configuration option value could not be converted to a specified type
*/
class CPPKAFKA_API InvalidConfigOptionType : public Exception {
public:
InvalidConfigOptionType(const std::string& config_name, const std::string& type);
};
/**
* A generic rdkafka handle error
*/

View File

@@ -64,6 +64,7 @@ public:
int32_t partition_count)>;
using ConfigurationBase<TopicConfiguration>::set;
using ConfigurationBase<TopicConfiguration>::get;
/**
* Default constructs a topic configuration object