Automatic cast to pointer without automatic cast to bool(-like) possible? - c++

Is is possible to create a class Wrapper such that
void f(void *) {}
Wrapper w;
f(w);
compiles, but
Wrapper w;
if (w) {}
doesn't compile? Or detect the difference at runtime?
Background: A win32 HANDLE is a typedef for void *. Win32 doesn't use NULL but instead ((HANDLE)(-1)) as an error value, so any code implicitly casting a HANDLE to bool is almost certainly testing the wrong thing. I have a class wrapping a HANDLE, and if possible I would like to remove this opportunity for errors when using the wrapper class.

In C++11 it is possible by using deleted functions. For instance:
struct Wrapper
{
operator void* () { }
operator bool () = delete;
};
void foo(void*) { }
int main()
{
Wrapper w;
foo(w); // OK
if (w) // ERROR!
{
// ...
}
}
If you are working with a compiler that does not support C++11, you can achieve the same result by declaring the bool conversion operator private:
struct Wrapper
{
operator void* () { }
private:
operator bool () { };
};
This works because accessibility of a function is verified only at the very last step of overload resolution.

Well, here's a version that works, but bear in mind that this is a terrible idea to have in production code:
struct Wrapper {
void *_value;
Wrapper() : _value(NULL) {
};
template<typename T>
Wrapper(T *value) : _value(value) {
};
void *operator &() {
return _value;
};
};
void func(void *value) {
printf("%p", value);
}
int main()
{
Wrapper w = (void *) 0xFFAABB;
if (w) // error, 'No viable conversion from 'Wrapper' to 'bool'
{
func(&w); // 0xffaabb
}
}
You cannot pass the wrapper directly, but passing the address of the wrapper will convert it to the address of the value.
Be very careful if you are trying to use this with external template functions, as they may not operate correctly.

Related

Merging a C struct factory function with its corresponding C++ wrapping class constructor

Consider writing a C++ wrapper for a C library with the following (T is some other type):
typedef struct { /*fields*/ } S;
S* alloc_S(const T*);
void free_S(S*);
I want to write a class class_S inheriting from S so that calls to alloc_S and free_S are hidden away thanks to, respectively, class_S::class_S(const T*) and class_S::~class_S() (removing the risk of forgetting a call to free_S).
As alloc_S already allocates and assigns values to all the fields of the structure it returns, is there an elegant way to build the rest of the class_S object "around" that structure?
My goal is to avoid the overhead (in time and space) of something like
class_S::class_S(const T* t)
{
S* tmp = alloc_S(t);
// deep-copy tmp into this
free_S(tmp);
}
Obviously, instead of inheriting from S, I could write class_S to have a S* member and work with it but, if possible, I would like to avoid this approach.
Here's one non-standard, confusing and unmaintainable way - note the special construction syntax
#include <memory>
extern "C" {
struct T {};
struct S
{
};
S* alloc_S(T*);
void free_S(S*);
}
struct class_S : S
{
void * operator new (std::size_t, T* p)
{
return alloc_S(p);
}
void operator delete(void *p)
{
if (p) free_S(reinterpret_cast<S*>(p));
}
};
int main()
{
T t;
auto ps = new (&t) class_S;
delete ps;
}
On balance you're probably better off using a unique_ptr with custom deleter:
struct class_S
{
struct deleter {
void operator()(S*p) const noexcept {
free_S(p);
}
};
class_S(T* p) : impl_(alloc_S(p), deleter()) {}
// add proxy methods as required
std::unique_ptr<S, deleter> impl_;
};
int main()
{
T t;
auto mys = class_S(&t);
}

How to provide const version of operator -> for a handle class

I am trying to overload my operator-> for a handle class to return const and non const pointer, pointing towards a base class.
Looking at the code i posted, in the trial function, if i add in the const keyword, the error message will be
||=== Build: Debug in Const trial (compiler: GNU GCC Compiler) ===|
C:\Const trial\main.cpp
||In function 'bool trial(Cards_pointer)':|
C:\Const trial\main.cpp|50|error: passing 'const Cards_pointer' as 'this' argument of 'Cards*& Cards_pointer::operator->()' discards qualifiers [-fpermissive]|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
My question is whether it is possible to do so, if yes, may i know what is the correct implementation?
#include <iostream>
#include<vector>
#include<stdexcept>
#include<algorithm>
using namespace std;
class Cards
{
private:
int x;
public:
Cards():x(3) {}
int rx()const
{
return x;
}
};
class Cards_pointer
{
private:
Cards* cp;
size_t* refptr;
public:
//default constructor
Cards_pointer():cp(0),refptr(new size_t(1)) {}
Cards_pointer(Cards*t):cp(t),refptr(new size_t(1)) {}
//copy constructor
Cards_pointer (const Cards_pointer&s):cp(s.cp),refptr(s.refptr)
{
refptr=s.refptr;
cp=s.cp;
//++*refptr;
*refptr=*refptr+1;
}
Cards*&operator->()
{
if(cp)
return cp;
else throw std::runtime_error("uninitialized Cards");
}
};
bool trial(const Cards_pointer x)
{
if(x->rx()==3)
return true;
return false;
}
int main()
{
Cards_pointer x=new Cards();
bool cond=trial(x);
}
Just return a pointer to const and provide a const qualified overload
class Something {
public:
void bar() {}
void foo() const {}
};
class Wrapper {
public:
Something* operator->() {
return &this->something;
}
const Something* operator->() const {
return &this->something;
}
private:
Something something;
};
int main() {
const auto c_wrapper = Wrapper{};
c_wrapper->foo();
// The below is an error
// c_wrapper->bar();
auto m_wrapper = Wrapper{};
m_wrapper->bar();
}
If you are worried about duplicated code in the const and non const overloads see Const function calling non const or vice versa (to avoid duplication)?
If you overload your operator->, the behaviour will not mimick that of built-in pointers (and will not make much sense at all).
Built-in pointers come in two flavours: pointers and pointers-to-const. (We ignore volatile here). These flavours are different types. Pointers themselves being const have nothing to do with constness of what they point to.
In order to imitate this behaviour, you need two flavours of Cards_pointer, one with operator-> that returns a normal pointer, and one with operator-> that returns a pointer-to-const.
class Cards_pointer_base { ... };
class Cards_pointer: private Cards_pointer_base {
public:
// usual constructors/assignment operators
using ...; // necessary members from the base
Cards* operator->() { ... }
};
class Cards_const_pointer: private Cards_pointer_base {
public:
// usual constructors/assignment operators
using ...; // necessary members from the base
const Cards* operator->() { ... }
// conversions from pointer to non-const
Cards_const_pointer(const Cards_pointer& from) { ... }
Cards_const_pointer& operator=(const Cards_pointer& from) { ... }
};
Standard smart pointers are class templates, so one can just write shared_ptr<Cards> and shared_ptr<const Cards>.

How to implement generically typed member objects in C++?

I have an application which creates simple music visualization animations. These animations are driven by nodes, and each node has a bunch of parameters that could have one of several types: int, float, color, etc. The parameters can either have a user-set value, or can be connected to the output of another node.
I'm currently using a templated type, along with std::function<>, like this:
#include <functional>
template <class PT>
class Param
{
public:
Param(PT value=PT()) : _value(value), _provider(nullptr) {}
void setValue(const PT &value) {_value = value;}
void setProvider(std::function<void(PT&)> provider) {_provider = provider;}
void getCurrentValue(PT &value) {
// update current member value
if (_provider)
_provider(_value);
value = _value;
}
private:
PT _value;
std::function<void(PT &value)> _provider;
};
I then instantiate parameters for an animated nodes like this:
class AnimationNode
{
public:
AnimationNode(Model *model = nullptr);
void evaluate();
private:
Param<int> _xoffset;
Param<int> _yoffset;
Param<float> _scale;
Param<ColorType> _color;
};
These parameters could be connected to a driver node, such as this one:
class SublevelMeter {
public:
SublevelMeter();
void setRange(Subrange &_range);
...
std::function<void(float&)> createProviderClosure();
private:
float _level;
...
}
std::function<void(float&)> SublevelMeter::createProviderClosure() {
return [this] (float &out) {out = _level;};
}
And connect one node to another by doing something like this:
AnimationNode::connectScaleToSublevel(SublevelMeter *slm) {
_scale->setProvider(slm->createProviderClosure());
}
The problem is, I'd like there to be an abstract Param type that I can pass to objects, so rather than the code above, I could pass a param to my SublevelMeter:
SublevelMeter::connectToParam(Param *param) {
param->setProvider(slm->createProviderClosure());
}
This would also help when writing the routines that create my GUI editor widgets: the editor could figure out the correct type by introspection of the Param.
But I'm not sure how to do this from a templated class, nor how the best way to implement the introspection in C++. (I'm coming at this from a python design background, which is perhaps encouraging me to think about this in a pythonic rather than C++ way; if there's a better way to approach this, I'd love to hear about it!)
I'm using Qt, so I've considered using QVariant, or other Qt Meta-Object stuff, but I'm not sure how to make that work, or if it would even be appropriate. (I'm not using Boost, and while I know it has certain type erasure facilities, I'm wary of wading into those waters...)
I'm interested in what the cleanest/"best" way to do this. Although efficiency is a consideration (getCurrentValue() is called many times per frame while the animation is playing) I can still probably afford run-time overhead of dynamic type stuff.
At least the first part of your question is solvable without abstract Param:
class SublevelMeter {
...
template<class PT>
void connectToParam(Param<PT> *param) {
param->setProvider(createProviderClosure<PT>());
}
// specialize this for different PTs
template<class PT>
std::function<void(PT&)> createProviderClosure();
}
If you really need to manipulate dynamic lists of Param-s, and you don't want to use any kind of RTTI, consider using Visitor pattern:
class Visitor;
class ParamBase
{
public:
virtual ~ParamBase() = default;
virtual void acceptVisitor(Visitor* v) = 0;
};
template <class PT>
class Param : public ParamBase
{
public:
...
void acceptVisitor(Visitor* v) override;
};
class Visitor {
public:
virtual ~Visitor() = default;
void visit(ParamBase* p) {
p->acceptVisitor(this);
}
virtual void visitParam(Param<float>* p) = 0;
// add more functions for other Params
};
class PrintVisitor : public Visitor {
public:
void visitParam(Param<float>* p) override {
std::cout << "visited Param<float>, value = " << p->getValue() << std::endl;
}
};
template<class PT>
void Param<PT>::acceptVisitor(Visitor* v) {
v->visitParam(this);
}
int main() {
std::unique_ptr<ParamBase> p(new Param<float>(123.4f));
std::unique_ptr<Visitor> v(new PrintVisitor());
v->visit(p.get());
return 0;
}
I implemented for you a simple class for the generic type management. This class is implemented without using template, so you can declare your variables and assign a value and a type directly at runtime. This implementation is very simple you should use it as reference to develop your own solution. In the following example I implemented the support for only 3 types: int, double and char* (C string). The main function shows you as to use the generic type class for both LVALUE and RVALUE assignment:
#include <stdio.h>
#include <stdlib.h>
enum Types {tInteger, tDouble, tString};
class TGenericType
{
private:
char m_Value[100];
Types m_Type;
protected:
public:
void operator=(int AValue)
{
m_Type = tInteger;
sprintf(m_Value, "%d", AValue);
}
operator int()
{
// try to convert the m_Value in integer
return atoi(m_Value); // the result depend by atoi() function
}
void operator=(double AValue)
{
m_Type = tDouble;
sprintf(m_Value, "%f", AValue);
}
operator double()
{
// try to convert the m_Value in double
return atof(m_Value); // the result depends by atof() function
}
void operator=(char* AValue)
{
m_Type = tString;
strcpy(m_Value, AValue);
}
operator char*()
{
return m_Value;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
TGenericType LVar;
// int assignment LVar used as LVALUE
LVar = 10;
// int assignment LVar used as RVALUE
int i = LVar;
// Double assignment LVar used as LValue
LVar = 10.1;
// double assignment LVar used as RVALUE
double d = LVar;
// costant string assignment LVar used as RVALUE
LVar = "Ciao Mondo";
// string copying LVar used as const string RVALUE
char Buffer[100];
strcpy(Buffer, LVar);
return 0;
}
I tested above code on c++builder 32bit and c++builder (CLang) 64bit
If my solution answer your question, please check it as answered.
Ciao from Italy!
Angelo

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).

instantiating a free template function within a template class

I need to instantiate a free template function (FTF) within a template class (TC). The FTF takes as a template parameter one of the template parameters of the TC. The TC also holds generic pointers to these FTF's, and these functions are called through the pointers.
The step of taking a pointer to a FTF is not enough to instantiate it, and I receive linker errors from the GCC toolchain. MSDN illustrates FTF specification as so -- however my instantion of the FTF is dependant on a template parameter of my TC, and therefore the FTF instantiation cannot be placed in free scope.
Is this possible ? I am attaching some basic generated code, the issue is in the constructor of the class test_service, where I assign the pointer of a free function into a custom container. I get a linker error telling me the free function cannot be found (uninstantiated). I know that specifying a call to the template function in the class somewhere will produce a instantiation, however I am only going to be making a call via a pointer.
#include "rpc_common.h"
#include <boost/cstdint.hpp>
namespace rubble { namespace rpc {
struct test_service_dummy_tag{};
template<typename T>
class test_service_skel
{
public:
bool Init() {}
bool TearDown() {}
bool test_one(TestRequest,TestResponse){};
private:
};
template<typename T_IMPL>
bool test_service_test_one(T_IMPL & impl,ClientRequest & request)
{
return 0;
}
template<typename T_IMPL=test_service_skel<test_service_dummy_tag> >
class test_service
{
public:
test_service()
{
// uncomment the following two lines and a instantiation will occur.
// ClientRequest cr;
//test_service_test_one<T_IMPL>(m_impl,cr);
m_dispatch_table.SetEntry( Oid("test_one",0),(void *) & test_service_test_one<T_IMPL>);
}
bool Init() { return m_impl.Init(); };
bool TearDown() { return m_impl.TearDown(); };
private:
T_IMPL m_impl;
OidContainer<Oid,void *> m_dispatch_table;
};
} }
EDIT: self-contained minimal version
class test_skel
{
bool test_function()
{
return true;
}
};
template<typename T>
bool test_function()
{
}
template<typename T = test_skel>
class test
{
public:
test()
{
dispatch = (void *) & test_function<T>;
}
void * dispatch;
};
int main()
{
test<> t;
return 0;
}
There is no problem iff you don't use a void*, i.e.: http://www.ideone.com/eRgUG
However, if you insist on storing the pointer in a void*, then you need to take the address using a specific function pointer first and then cast - e.g.
bool (*temp)() = &test_function<T>;
dispatch = reinterpret_cast<void*>(temp); // YUCK
This gives the compiler enough context to generate the address for you.
Ahh - just saw DeadMG's answer, the function to generate the void* is neater...
Your self-contained example wouldn't compile for me with a strange error about overloaded functions, when there is no overloading going on, with MSVC. I did, however, manage to work around it.
class test_skel
{
bool test_function()
{
return true;
}
};
template<typename T> void* to_void_pointer(T t) {
return reinterpret_cast<void*>(t);
}
template<typename T>
bool test_function()
{
return true;
}
template<typename T = test_skel>
class test
{
public:
test()
{
dispatch = to_void_pointer(&test_function<T>);
}
void * dispatch;
};
int main()
{
test<> t;
return 0;
}
This compiles cleanly. I suspect that whatever behaviour you're seeing and I saw is a compiler error.