【问题标题】:Interfaces with Template methods带有模板方法的接口
【发布时间】:2012-08-30 23:20:11
【问题描述】:

我需要定义一个配置对象。我正在使用boost::property_tree 作为 impl,但我不想在我的界面中公开 Impl 详细信息,或者必须在我的界面中使用#include boost 文件。 问题是我想使用ptree的模板方法来获取值,

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

但这是不可能的(?)

// 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;
 }

一种选择是限制我可以“获取”的类型,例如:

// 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;
 }

但这很丑陋且不可扩展。
还有更好的选择吗?

【问题讨论】:

  • 请注意,不能单独对返回类型进行重载,因此第二个代码 sn-p 也不会编译。限制对我来说似乎是合理的,让 get_string() 返回一个 std::string 给调用者,然后调用者可以在必要时将其转换为另一种类型。
  • 或者你可以返回一个boost::any...
  • 这里有getter的调用语法m_ptree.get&lt;int&gt;(key),因为你必须以某种方式指定返回值的类型。您不能在自己的代码中使用相同的技术吗?

标签: c++ oop boost interface


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你不能有虚函数模板——但你可以使用另一种接口技术,它被称为 Pimpl idiom。

    herehere

    【讨论】:

      猜你喜欢
      • 2013-04-13
      • 2011-11-03
      • 1970-01-01
      • 2017-08-17
      • 1970-01-01
      • 2011-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多