C++ 自动类型转换

C++ 自动类型转换,c++,proxy,wrapper,C++,Proxy,Wrapper,假设我有这样一个类(注意,这是根据Stroustrup建立的: template<class T> struct Wrapper { private: //This class is implicitly convertable to T& struct TempRef { operator T&(); T& operator()(); ~TempRef(); //Executes clean up

假设我有这样一个类(注意,这是根据Stroustrup建立的:

template<class T>
struct Wrapper
{

  private:

  //This class is implicitly convertable to T&
  struct TempRef 
  { 
     operator T&(); 
     T& operator()(); 
     ~TempRef();   //Executes clean up code
  };
  struct TempPtr 
  { 
    T* operator T->(); 
    ~TempPtr();  //Executes clean up code
  };

  public:
  TempRef operator*();
  TempPtr operator->();

};
当我想将其用作整型的包装器时,问题就出现了:

Wrapper<int> var;
//*var = 12;  //Oops!! Does not work (no automatic conversion)
((int&)(*var)) = 12; //Works but the syntax is a pain
(*var)() = 12;  //Good but still could be better
Wrapper变量;
//*var=12;//Oops!!不工作(无自动转换)
((int&)(*var))=12;//可以工作,但语法很麻烦
(*var)(=12;//很好,但还可以更好
所以问题是:


有没有办法使使用
Wrapper
作为整数类型的包装的语法与指向整数类型的指针相同,或者这在目前是不可能的?

您需要在
Wrapper
中定义赋值运算符。类似于

Wrapper<T> &operator=(const T &v) {
    /*something to get the T& returned by TempRef::operator T&*/ = v;
    return *this;
}
Wrapper&operator=(常量T&v){
/*获取TempRef::运算符T&*/=v返回的T&的内容;
归还*这个;
}

这将被
var=12;

调用。它对指针没有更好的效果。您正在测试两个不同的东西。尝试分配到一个包装指针。是的……这很完美……只需要为所有其他运算符创建一个,然后它就可以完美地工作……当然,只有在t具有该操作时才使用enable。。。。。..
Wrapper<T> &operator=(const T &v) {
    /*something to get the T& returned by TempRef::operator T&*/ = v;
    return *this;
}