gpt4 book ai didi

具有从模板多重继承的 C++ 重载运算符

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:53 25 4
gpt4 key购买 nike

我有一个表示 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在编译期间。所以,问题是:

  • 为什么会失败以及如何解决?
  • 这样做是合理的还是有更简单的设计?

最佳答案

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

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

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

Live example

关于具有从模板多重继承的 C++ 重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19159784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com