C ++重载运算符,具有来自模板的多重继承

时间:2013-10-03 12:55:24

标签: c++ templates inheritance operator-overloading

我有一个代表HTTP客户端某些部分的层次结构,如下所示:

typedef list<pair<string, string> > KeyVal;
struct Header { string name; string value; ...};
struct Param { string name; string value; ...};

/* Something that contains headers */
template<typename T> class WithHeaders {
  KeyVal headers;
public:
  virtual T &operator <<(const Header &h) {
    headers.push_back(pair<string, string>(h.name, h.value));
    return static_cast<T&> (*this);
  }
};

/* Something that contains query params */
template<class T> class WithQuery {
    KeyVal query_params;

public:
    virtual T &operator <<(const Param &q) {
      query_params.push_back(pair<string, string>(q.name, q.value));
      return static_cast<T&> (*this);
    }

    const KeyVal &get_query() const {return query_params;}
};

/* Http Request has both headers and query parameters */
class Request: public WithQuery<Request>, public WithHeaders<Request> {...};

因此我希望能够执行request << Header(name, value) << Param("page", "1")之类的操作(稍后会在相应的WithHeaders类中重用Response)。

我正在尝试编译的代码是:

Request rq = Request("unused", "unused", "unused");
rq << Header("name", "value");

但是,我得到了:

test/test_client.cpp:15:30: error: request for member ‘operator<<’ is ambiguous
In file included from test/test_client.cpp:1:0:
test/../client.h:45:16: error: candidates are: 
    T& WithQuery<T>::operator<<(const Param&) [with T = Request]         
    T& WithHeaders<T>::operator<<(const Header&) [with T = Request]

我必须遗漏一些东西,但在编译期间似乎很容易区分ParamHeader。所以,问题是:

  • 为什么会失败以及如何解决?
  • 这是一个合理的事情,还是设计更简单?

1 个答案:

答案 0 :(得分:5)

我认为它应该有效,所以它很可能是一个GCC错误。 正如@refp在评论中指出的那样,查找实际上是不明确的,而GCC在拒绝它时是正确的。

这就是你如何运作:

class Request: public WithQuery<Request>, public WithHeaders<Request> {
public:
    using WithHeaders<Request>::operator<<;
    using WithQuery<Request>::operator<<;
};

Live example