6

我有一个层次结构,它代表 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]

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

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

1 回答 1

5

我相信它应该可以工作,所以它很可能是一个 GCC 错误。 正如@refp 在评论中指出的那样,查找实际上是模棱两可的,GCC 拒绝它是正确的。

这就是你让它工作的方式:

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

活生生的例子

于 2013-10-03T13:17:55.317 回答