-
Operators
I am trying some funky stuff here...
Code:
template<class t>
class b {
public:
b(){}
t* operator()(int x)
{
return objs[x];
}
void Add(t* p)
{
objs.push_back(p);
}
private:
std::vector<t*> objs;
};
template<class t>
class a {
public:
a(){}
b<t>* operator->()
{
return &m_b;
}
private:
b<t> m_b;
};
...
int main() {
a<plug> plugs;
plugs->Add(&plug());
plugs->Add(&plug_derived());
plugs->(0)->print(); // ugly compile time error here...
plugs->operator()(0)->print(); // just fine...
}
So, my question is, why do I have to call the operator as a function, instead of as an operator? Can I get around this?
Z.
-
Re: Operators
note that C++ isn't a too funky language, so you can't do everything you want. I lookedup MSVC language reference and didn't find that operator listed :/
-
The parens operator exists (the code I posted compiles if you remove the line that I commented gets the error). I just want to know why that calling style doesnt work =).
Z.
-
Because (0) is not a member of the class. You can either call the function "operator ()" of the class or use () directly, but that doesn't work with pointers. This should work:
b<plug>* pB;
(*pB)(0)->print();
but when you use the -> operator to access a pointer to class b I don't know. Maybe this:
(*(plugs->))(0)->print();
Bu you could also overload the dereference operator (* without arguments) in a, then do:
(*plugs)(0)->print();
-
Too bad I can overload the -> operator to return a b<t>&. Thanks a bunch!
Z.