2

I need to define a Configuration object. I am using boost::property_tree for the impl, but I do not want to expose Impl details in my interface, or have to #include boost files in my interface. The problem is that I would like to use the template method of ptree for getting values,

template <typename T>
T get(const std::string key)

But this is impossible (?)

// Non compilable code (!)
// Interface
class Config {
public:
   template <typename T>
   T get(const std::string& key);
 }

 // Impl
 #include "boost/property_tree.h"

class ConfigImpl : public Config {
public:
   template <typename T>
   T get(const std::string& key) {
      return m_ptree.get(key);
   }

 private:
   boost::ptree m_ptree;
 }

One option is to limit the types I can "get", for instance:

// Interface
class Config {
public:
   virtual int get(const std::string& key) = 0;
   virtual const char* get(const std::string& key) = 0;
 }

 // Impl
 #include "boost/property_tree.h"

class ConfigImpl : public Config {
public:
   virtual int get(const std::string& key) { return m_ptree.get<int>(key) };
   virtual const char* get(const std::string& key) { return m_ptree.get<const char*>(key); }

 private:
   boost::ptree m_ptree;
 }

But this is pretty ugly and not scalable.
Any better options out there?

4

2 回答 2

3

You cannot have virtual function templates - but you coul'd use another interface technique, which is called Pimpl idiom.

See here and here

于 2012-09-06T07:41:11.643 回答
0

您必须使用模板和类型擦除来实现此目的,请观看此 cppcon 视频,名为:实用类型擦除。(https://www.youtube.com/watch?v=5PZVuUzP34g

于 2017-07-26T12:14:14.330 回答