- #1
- 14,983
- 26
Allow me to present a simplified version of what I'm doing: (yes, I have a reason to do this.
)
To summarize:
I wish to create a class that acts as a reference type.
I would like to be able to pass my custom reference type into any template function that expects an actual reference.
But here's the problem: C++ doesn't let you make a non-constant reference to a temporary object.
Since it would be rather painful for me to overload every function I might ever want to call to take any combination of the reference types I'm writing, and for every function I develop to have multiple versions, I would like a more automatic approach.
Thus, I provided a conversion into (wrapper&). g++, at least, is happy with it.
Is this valid C++?
Code:
class wrapper
{
private:
int &v;
public:
wrapper(int &value):v(value) {}
wrapper& operator=(int value) {
v = value;
return *this;
}
// This is the questionable bit:
operator wrapper&() { return *this; }
};
wrapper make_wrapper(int &value)
{
return wrapper(value);
}
template <typename T>
void foo(T &t)
{
t = 1;
}
int main()
{
int x;
foo(make_wrapper(x));
}
To summarize:
I wish to create a class that acts as a reference type.
I would like to be able to pass my custom reference type into any template function that expects an actual reference.
But here's the problem: C++ doesn't let you make a non-constant reference to a temporary object.
Since it would be rather painful for me to overload every function I might ever want to call to take any combination of the reference types I'm writing, and for every function I develop to have multiple versions, I would like a more automatic approach.
Thus, I provided a conversion into (wrapper&). g++, at least, is happy with it.
Is this valid C++?