gpt4 book ai didi

c++ - 模板化运算符[] ...可能吗?有用?

转载 作者:太空狗 更新时间:2023-10-29 23:38:06 28 4
gpt4 key购买 nike

你能不能:

template <class T>
const T &operator[] (unsigned int x)

我的想法是如果你有一个 map<string,string>如果有一个包装器类可以让您这样做,那就太好了:

obj["IntVal"]="12";
obj["StringVal"]="Test";

int i = obj["IntVal"];

在 C++ 中,我们实际上能做到多接近这一点?值得这样痛苦吗?

最佳答案

你也可以这样做

class Class {
struct Proxy {
template<typename T> T as() { ... }
template<typename T> operator T() { return as<T>(); }
private:
Proxy(...) { ... }
Proxy(Proxy const&); // noncopyable
Proxy &operator=(Proxy const&);
friend class Class;
};

public:
Proxy operator[](std::string const& s) { ... }
};

Class a;
int i = a["foo"];
int i = a["foo"].as<int>();

T将被推断为要初始化的对象是什么。并且您不得复制代理。也就是说,我更喜欢明确的 as<T>功能也像另一个提议的那样。

关于c++ - 模板化运算符[] ...可能吗?有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2381232/

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