给出以下代码:
template <typename T>
struct Wrapper {
T value;
Wrapper(T val) : value(val) {}
}
int main() {
Wrapper<int> x(42);
int y = x; // need solution for y = x.value
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法实现分配
int y = x;
Run Code Online (Sandbox Code Playgroud)
所以它意味着y = x.value.
我知道重载赋值运算符本身是不可能的,因为它适用于赋值左侧的对象,而标准不允许带有两个参数的friend函数.
如果通过重载任何其他运算符或使用一些特殊技巧无法做到这一点,除非通过调用Wrapper类提供的get方法,除非通过调用Wrapper类提供的get方法,否则将如何实现:
int y = x.get();
Run Code Online (Sandbox Code Playgroud) 请考虑以下示例:
class MyContainer {
std::vector<void *> v;
public:
void Put(void *x) { v.push_back(x);}
void* Get(int index) { return v[index];}
};
void Work (MyContainer& c) {
// cast_to_type(c.Get(0));
}
int main() {
int x = 1;
double y = 2.0;
MyContainer c;
c.Put(&x);
c.Put(&y);
Work(c);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
假设函数Work对向量指针指向的对象一无所知.还假设继承不是一个选项,并且指向对象的类型可以是任意的(可以有无数种类型).
是否可以仅使用MyContainer::Get函数返回的void指针来推断类型?可以使用演员表,模板和typeid操作员的任意组合来完成吗?