Implicit invocation of operator [C++] - c++

I defined two classes:
class Token_
{
public:
virtual char operator*()const = 0;//this fnc cannot run implicitly
protected:
Token_()
{ }
Token_(const Token_&);
Token_& operator=(const Token_&);
};
and second:
class Operator : public Token_
{
public:
Operator(const char ch):my_data_(token_cast<Operator_enm>(ch))
{ }
Operator_enm get()const
{
return my_data_;
}
Operator_enm set(const Operator_enm& value)
{
Operator_enm old_value = get();
my_data_ = value;
return old_value;
}
char operator*()const//this operator has to be invoke explicitly
{
return static_cast<char>(my_data_);
}
private:
Operator_enm my_data_;
};
and later on in program I have something like this:
template<class R>
R Calculator::expr_()const
{
Token_* token = read_buffer_();
switch (*token)//here if I use explicit call of operator*() it works
{
case PLUS:
{
R result ;//not defined yet
return result;
}
case MINUS:
{
R result ;//not defined yet
return result;
}
default:
cerr << "Bad expr token.";
}
}
Why this call of operator*() can't be implicit? Is there any way to make it implicit?
Thank you.

token is a pointer to a Token_ object, not a Token_ object itself, thus the * operator in the switch statement dereferences only the pointer (thereby only obtaining the object), but doesn't then continue to call the operator you defined.
Try instead:
switch(*(*token)) {
The use of your custom operator * might be a bit confusing now though.
Another options is to alter read_buffer_() such that you can do the following:
Token_ token = read_buffer_(); // NOTE: read_buffer_() returns a Token_ object directly
switch (*token)//here if I use explicit call of operator*() it works
In that case, Token_ objects mimic pointers, and you wouldn't return pointer to pointers normally either.

The other option is instead of:
Token_* token = read_buffer_();
do:
Token_& token = *read_buffer_();

Related

wrong number of template arguments (3, should be 4)

I tried to use property on c++ to use it instead of too many setter and getter function in data class have lots of member variable.
there are two property class. first one has fixed setter and getter function by default set, get. second one support using custom setter and getter function of its class. below is the code
template <class T>
class Property
{
T data;
public:
// access with function call syntax
Property() : data() { }
T operator()() const
{
return data;
}
T operator()( T const & value)
{
data = value;
return data;
}
// access with get()/set() syntax
T get() const
{
return data;
}
T set( T const & value )
{
data = value;
return data;
}
// access with '=' sign
operator T() const
{
return data;
}
T operator = ( T const & value )
{
data = value;
return data;
}
typedef T value_type; // might be useful for template deductions
};
// a read-write property which invokes user-defined functions
template <class T, class Object, T(Object::*real_getter)(), T(Object::*real_setter)(T const &) >
class RWProperty
{
Object * my_object;
public:
// this function must be called by the containing class, normally in a
// constructor, to initialize the RWProperty so it knows where its
// real implementation code can be found
void operator () ( Object * obj )
{
my_object = obj;
}
// function call syntax
T operator()() const
{
return (my_object->*real_getter)();
}
T operator()( T const & value )
{
return (my_object->*real_setter)( value );
}
// get/set syntax
T get() const
{
return (my_object->*real_getter)();
}
T set( T const & value )
{
return (my_object->*real_setter)( value );
}
// access with '=' sign
operator T() const
{
return (my_object->*real_getter)();
}
T operator = ( T const & value )
{
return (my_object->*real_setter)( value );
}
typedef T value_type; // might be useful for template deductions
};
and i'm testing these properties in OptionSet class before putting it into project code
#include <QString>
class OptionSet
{
public:
explicit OptionSet() {}
Property<QString> m_MeshMode;
RWProperty<uint, OptionSet, &getNumberOfVbo, &setNumberOfVbo> uNumberOfVbo;
// this causes problems
protected:
private:
Property<uint> m_uNumberOfVbo;
uint setNumberOfVbo(const uint& rVboCount)
{
// something to do here
return m_uNumberOfVbo(rVboCount);
}
uint getNumberOfVbo() const
{
return m_uNumberOfVbo();
}
};
but in use RWProperty, even i passed 4 arguments of template like member type, class type has setter and getter function, getter function pointer, setter function pointer in order, it says
"wrong number of template arguments (3, should be 4) :
RWProperty <uint, OptionSet, &getNumberOfVbo, &setNumberOfVbo>
uNumberOfVbo"
"provided for 'template<class T, class Object,
T(Object::*real_getter)(), T(Object::*real_setter)(const T&)> class
RWProperty : class RWProperty"
I guess i'm doing something wrong to pass arguments in template.
is there anyone knows what happened?
There are three mistakes in your code:
Firstly, to get the address of a member function, you need to include the class name:
RWProperty<uint, OptionSet
, &OptionSet::getNumberOfVbo
// ~~~~~~~~~~~^
, &OptionSet::setNumberOfVbo> uNumberOfVbo;
// ~~~~~~~~~~~^
Secondly, to form a pointer to const qualified member function, you need to append const keyword to the declaration of that pointer:
T (Object::*real_getter)() const
// ~~~~^ to match 'uint getNumberOfVbo() const'
Lastly, OptionSet inside OptionSet itself is an incomplete type. You can't refer to its member unless the point of declaration of that member comes first. This basically means you need to reorder your declarations within OptionSet so that setNumberOfVbo and getNumberOfVbo comes before you declare uNumberOfVbo data member:
class OptionSet
{
//...
uint setNumberOfVbo(const uint& rVboCount) { /*...*/ }
uint getNumberOfVbo() const { /*...*/ }
// Ok, now they are known and can be found in the class scope
//...
RWProperty<uint, OptionSet
, &OptionSet::getNumberOfVbo
, &OptionSet::setNumberOfVbo> uNumberOfVbo;
};

Overload -> operator to forward member-access through Proxy

I'm trying to wrap a Python PyObject* in an Object class.
In Python, everything is a PyObject*.
A list is a PyObject*, and each item in the list is itself a PyObject*.
Which could even be another list.
etc.
I'm trying to allow fooList[42] = barObj style syntax by means of a Proxy pattern (here).
Now that I have that working, I want to extend it so that fooList[42] can be used as an Object. Specifically I want to be able to handle...
fooList[42].myObjMethod()
fooList[42].myObjMember = ...
Object has a lot of methods, and currently fooList[42].myObjMethod() is going to first resolve fooList[42] into a Proxy instance, say tmpProxy, and then attempt tmpProxy.myObjMethod().
This means I would have to do
void Proxy::myObjMethod(){ return wrapped_ob.myObjMethod(); }
i.e. manually relay each of Object's methods through Proxy, which is ugly.
I can't see any perfect solution (see the above linked answer), but I would be happy to use:
fooList[42]->myObjMethod()
... as a compromise, seeing as -> can be overloaded (as opposed to . which cannot).
However, I can't find any documentation for overloading operator->.
My best guess is that it must return a pointer to some object (say pObj), and C++ will invoke pObj->whatever.
Below is my attempted implementation. However, I'm running into a 'taking the address of a temporary object of type Object' warning.
I have, within my Object class:
const Object operator[] (const Object& key) const {
return Object{ PyObject_GetItem( p, key.p ) };
}
NOTE that 'const Object&' runs into 'taking the address of a temporary object of type Object' warning.
class Proxy {
private:
const Object& container;
const Object& key;
public:
// at this moment we don't know whether it is 'c[k] = x' or 'x = c[k]'
Proxy( const Object& c, const Object& k ) : container{c}, key{k}
{ }
// Rvalue
// e.g. cout << myList[5] hits 'const Object operator[]'
operator Object() const {
return container[key];
}
// Lvalue
// e.g. (something = ) myList[5] = foo
const Proxy& operator= (const Object& rhs_ob) {
PyObject_SetItem( container.p, key.p, rhs_ob.p );
return *this; // allow daisy-chaining a = b = c etc, that's why we return const Object&
}
const Object* operator->() const { return &container[key]; }
// ^ ERROR: taking the address of a temporary object of type Object
};
The idea is to allow myList[5]->someMemberObj = ... style syntax.
myList[5] resolves as a Proxy instance, which is wrapping an Object (the sixth element of myList). Let's call it myItem.
Now I want someProxy->fooFunc() or someProxy->fooProperty to invoke myItem.fooFunc() or myItem.fooProperty respectively.
I'm running into a 'taking the address of a temporary object of type Object' warning.
If you can change Object, you may add
class Object {
public:
// other code
const Object* operator -> () const { return this; }
Object* operator -> () { return this; }
};
And for your Proxy
Object operator->() { return container[key]; }
So, for example
myObj[42]->myFoo = ...
is mostly equivalent to
Proxy proxy = myObj[42];
Object obj = proxy.operator ->();
Object* pobj = obj.operator ->(); // so pobj = &obj;
pobj->myFoo = ...
I find the Proxy class that you wrote as an example a bit confusing so i took the liberty to change it a little:
Here is a simple example:
//object with lots of members:
class my_obj
{
public:
std::string m_text;
void foo()
{
std::cout << m_text << std::endl;
}
void bar(std::string t)
{
m_text = t;
}
};
//proxy object
class proxy_class
{
private:
friend class CustomContainer;
my_obj* px;
proxy_class(my_obj * obj_px)
:px(obj_px)
{
}
proxy_class() = delete;
proxy_class(const proxy_class &) = delete;
proxy_class& operator =(const proxy_class &) = delete;
public:
my_obj* operator ->()
{
return px;
}
};
//custom container that is the only one that can return proxy objects
class CustomContainer
{
public:
std::map<std::size_t, my_obj> stuff;
proxy_class operator [](const std::size_t index)
{
return proxy_class(&stuff[index]);
}
};
example usage:
CustomContainer cc;
cc[0]->foo();
cc[0]->bar("hello world");
cc[0]->foo();
As a design consideration the proxy class should be create in a controlled environment so constructors are removed from preventing miss-usage.
CustomContainer has to only return proxy_class with a reference to my_obj so it can use anything, std::map, std::vector, etc
After several hours of coaxing coliru, I have a working testcase.
Please refer to: https://codereview.stackexchange.com/questions/75237/c11-proxy-pattern-for-supporting-obidx-someobjmember-type-acc
Many thanks to Jarod, for supplying the correct syntax and understanding for -> overload.

How do I make a class in C++, when initialized, return a boolean value when its name is invoked, but no explicit function call make, like ifstream

How do I make a class in C++, when initialized, return a Boolean value when its name is invoked, but no explicit function call make, like ifstream. I want to be able to do this:
objdef anobj();
if(anobj){
//initialize check is true
}else{
//cannot use object right now
}
not just for initialization, but a check for its ability to be used.
The way istream does it is by providing an implicit conversion to void*
http://www.cplusplus.com/reference/iostream/ios/operator_voidpt/
stream output and implicit void* cast operator function invocation
Update In reaction to the comments, the Safe Bool Idiom would be a far better solution to this: (code directly taken from that page)
class Testable {
bool ok_;
typedef void (Testable::*bool_type)() const;
void this_type_does_not_support_comparisons() const {}
public:
explicit Testable(bool b=true):ok_(b) {}
operator bool_type() const {
return ok_==true ?
&Testable::this_type_does_not_support_comparisons : 0;
}
};
template <typename T>
bool operator!=(const Testable& lhs,const T& rhs) {
lhs.this_type_does_not_support_comparisons();
return false;
}
template <typename T>
bool operator==(const Testable& lhs,const T& rhs) {
lhs.this_type_does_not_support_comparisons();
return false;
}
The article by Bjorn Karlsson contains a reusable implementation for the Safe Bool Idiom
Old sample:
For enjoyment, I still show the straight forward implementation with operator void* overloading, for clarity and also to show the problem with that:
#include <iostream>
struct myclass
{
bool m_isOk;
myclass() : m_isOk(true) { }
operator void* () const { return (void*) (m_isOk? 0x1 : 0x0); }
};
myclass instance;
int main()
{
if (instance)
std::cout << "Ok" << std::endl;
// the trouble with this:
delete instance; // no compile error !
return 0;
}
This is best accomplished using the safe bool idiom.
You provide an implicit conversion to a member-function-pointer, which allows instances of the type to be used in conditions but not implicitly convertyed to bool.
You need a (default) constructor and an operator bool()().
class X {
public:
operator bool ()const{
//... return a boolean expression
}
};
usage:
X x; // note: no brackets!
if( x ) {
....
}
You'll want to create an operator bool function (or as boost does, an unspecified_bool_type that has certain improved properties I can't recall offhand). You may also want to create operator! (For some reason I seem to recall iostreams do this too).

Chaining calls to temporaries in C++

I have a class that does a transformation on a string, like so
class transer{
transer * parent;
protected:
virtual string inner(const string & s) = 0;
public:
string trans(const string & s) {
if (parent)
return parent->trans(inner(s));
else
return inner(s);
}
transer(transer * p) : parent(p) {}
template <class T>
T create() { return T(this); }
template <class T, class A1> // no variadic templates for me
T create(A1 && a1) { return T(this, std::forward(a1)); }
};
So I can create a subclass
class add_count : public transer{
int count;
add_count& operator=(const add_count &);
protected:
virtual string inner(const string & s) {
return std::to_string((long long)count++) + s;
}
public:
add_count(transer * p = 0) : transer(p), count(0) {}
};
And then I can use the transformations:
void use_transformation(transer & t){
t.trans("string1");
t.trans("string2");
}
void use_transformation(transer && t){
use_trasnformation(t);
}
use_transformation(add_count().create<add_count>());
Is there a better design for this? I'd like to avoid using dynamic allocation/shared_ptr if I can, but I'm not sure if the temporaries will stay alive throughout the call. I also want to be able to have each transer be able to talk to its parent during destruction, so the temporaries also need to be destroyed in the right order. It's also difficult to create a chained transformation and save it for later, since
sometrans t = add_count().create<trans1>().create<trans2>().create<trans3>();
would save pointers to temporaries that no longer exist. Doing something like
trans1 t1;
trans2 t2(&t1);
trans3 t3(&t2);
would be safe, but annoying. Is there a better way to do these kinds of chained operations?
Temporaries will be destructed at the end of the full expression, in the
reverse order they were constructed. Be careful about the latter,
however, since there are no guarantees with regards to the order of
evaluation. (Except, of course, that of direct dependencies: if you
need one temporary in order to create the next—and if I've
understood correctly, that's your case—then you're safe.)
If you don't want dynamic allocation you either pass the data which is operated on to the function that initiates the chain, or you need a root type which holds it for you ( unless you want excessive copying ). Example ( might not compile ):
struct fooRef;
struct foo
{
fooRef create() { return fooRef( m_Val ); }
foo& operator=( const fooRef& a_Other );
std::string m_Val;
}
struct fooRef
{
fooRef( std::string& a_Val ) : m_Val( a_Val ) {}
fooRef create() { return fooRef( m_Val ); }
std::string& m_Val;
}
foo& foo::operator=( const fooRef& a_Other ) { m_Val = a_Other.m_Val; }
foo startChain()
{
return foo();
}
foo expr = startChain().create().create(); // etc
First the string lies on the temporary foo created from startChain(), all the chained operations operates on that source data. The assignment then at last copies the value over to the named var. You can probably almost guarantee RVO on startChain().

What is purpose of a "this" pointer in C++? [duplicate]

This question already has answers here:
When should I make explicit use of the `this` pointer?
(12 answers)
Closed 6 years ago.
What is purpose of this keyword. Doesn't the methods in a class have access to other peer members in the same class ? What is the need to call a this to call peer methods inside a class?
Two main uses:
To pass *this or this as a parameter to other, non-class methods.
void do_something_to_a_foo(Foo *foo_instance);
void Foo::DoSomething()
{
do_something_to_a_foo(this);
}
To allow you to remove ambiguities between member variables and function parameters. This is common in constructors.
MessageBox::MessageBox(const string& message)
{
this->message = message;
}
(Although an initialization list is usually preferable to assignment in this particular example.)
Helps in disambiguating variables.
Pass yourself as a parameter or return yourself as a result
Example:
struct A
{
void test(int x)
{
this->x = x; // Disambiguate. Show shadowed variable.
}
A& operator=(A const& copy)
{
x = copy.x;
return *this; // return a reference to self
}
bool operator==(A const& rhs) const
{
return isEqual(*this, rhs); // Pass yourself as parameter.
// Bad example but you can see what I mean.
}
private:
int x;
};
Consider the case when a parameter has the same name as a class member:
void setData(int data){
this->data = data;
}
Resolve ambgiguity between member variables/functions and those defined at other scopes
Make explicit to a reader of the code that a member function is being called or a member variable is being referenced.
Trigger IntelliSense in the IDE (though that may just be me).
The expression *this is commonly used to return the current object from a member function:
return *this;
The this pointer is also used to guard against self-reference:
if (&Object != this) {
// do not execute in cases of self-reference
It lets you pass the current object to another function:
class Foo;
void FooHandler(Foo *foo);
class Foo
{
HandleThis()
{
FooHandler(this);
}
};
Some points to be kept in mind
This pointer stores the address of
the class instance, to enable pointer
access of the members to the member
functions of the class.
This pointer is not counted for
calculating the size of the object.
This pointers are not accessible for
static member functions.
This pointers are not modifiable
Look at the following example to understand how to use the 'this' pointer explained in this C++ Tutorial.
class this_pointer_example // class for explaining C++ tutorial
{
int data1;
public:
//Function using this pointer for C++ Tutorial
int getdata()
{
return this->data1;
}
//Function without using this pointer
void setdata(int newval)
{
data1 = newval;
}
};
Thus, a member function can gain the access of data member by either using this pointer or not.
Also read this to understand some other basic things about this pointer
It allows you to get around members being shadowed by method arguments or local variables.
The this pointer inside a class is a reference to itself. It's needed for example in this case:
class YourClass
{
private:
int number;
public:
YourClass(int number)
{
this->number = number;
}
}
(while this would have been better done with an initialization list, this serves for demonstration)
In this case you have 2 variables with the same name
The class private "number"
And constructor parameter "number"
Using this->number, you let the compiler know you're assigning to the class-private variable.
For example if you write an operator=() you must check for self assignment.
class C {
public:
const C& operator=(const C& rhs)
{
if(this==&rhs) // <-- check for self assignment before anything
return *this;
// algorithm of assignment here
return *this; // <- return a reference to yourself
}
};
The this pointer is a way to access the current instance of particular object. It can be used for several purposes:
as instance identity representation (for example in comparison to other instances)
for data members vs. local variables disambiguation
to pass the current instance to external objects
to cast the current instance to different type
One more purpose is to chaining object:
Consider the following class:
class Calc{
private:
int m_value;
public:
Calc() { m_value = 0; }
void add(int value) { m_value += value; }
void sub(int value) { m_value -= value; }
void mult(int value) { m_value *= value; }
int getValue() { return m_value; }
};
If you wanted to add 5, subtract 3, and multiply by 4, you’d have to do this:
#include
int main()
{
Calc calc;
calc.add(5); // returns void
calc.sub(3); // returns void
calc.mult(4); // returns void
std::cout << calc.getValue() << '\n';
return 0;
}
However, if we make each function return *this, we can chain the calls together. Here is the new version of Calc with “chainable” functions:
class Calc
{
private:
int m_value;
public:
Calc() { m_value = 0; }
Calc& add(int value) { m_value += value; return *this; }
Calc& sub(int value) { m_value -= value; return *this; }
Calc& mult(int value) { m_value *= value; return *this; }
int getValue() { return m_value; }
};
Note that add(), sub() and mult() are now returning *this. Consequently, this allows us to do the following:
#include <iostream>
int main()
{
Calc calc;
calc.add(5).sub(3).mult(4);
std::cout << calc.getValue() << '\n';
return 0;
}
We have effectively condensed three lines into one expression.
Copied from :http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/
Sometimes you want to directly have a reference to the current object, in order to pass it along to other methods or to store it for later use.
In addition, method calls always take place against an object. When you call a method within another method in the current object, is is equivalent to writing this->methodName()
You can also use this to access a member rather than a variable or argument name that "hides" it, but it is (IMHO) bad practice to hide a name. For instance:
void C::setX(int x)
{
this->x = x;
}
For clarity, or to resolve ambiguity when a local variable or parameter has the same name as a member variable.
It also allows you to test for self assignment in assignment operator overloads:
Object & operator=(const Object & rhs) {
if (&rhs != this) {
// do assignment
}
return *this;
}
It also allows objects to delete themselves. This is used in smart pointers implementation, COM programming and (I think) XPCOM.
The code looks like this (excerpt from some larger code):
class counted_ptr
{
private:
counted_ptr(const counted_ptr&);
void operator =(const counted_ptr&);
raw_ptr_type _ptr;
volatile unsigned int _refcount;
delete_function _deleter;
public:
counted_ptr(raw_ptr_type const ptr, delete_function deleter)
: _ptr(ptr), _refcount(1), _deleter(deleter) {}
~counted_ptr() { (*_deleter)(_ptr); }
unsigned int addref() { return ++_refcount; }
unsigned int release()
{
unsigned int retval = --_refcount;
if(0 == retval)
>>>>>>>> delete this;
return retval;
}
raw_ptr_type get() { return _ptr; }
};
The double colon in c++ is technically known as "Unary Scope resolution operator".
Basically it is used when we have the same variable repeated for example inside our "main" function (where our variable will be called local variable) and outside main (where the variable is called a global variable).
C++ will alwaysexecute the inner variable ( that is the local one).
So imagine you want to use the global variable "Conundrum" instead the local one just because the global one is expressed as a float instead of as an integer:
#include <iostream>
using namespace std;
float Conundrum=.75;
int main()
{
int Conundrum =75;
cout<<::Conundrum;
}
So in this case the program will use our float Conundrum instead of the int Conundrum.