I have two classes,
template<class Type>
class SafePtr {
public:
SafePtr() {}
~SafePtr() {}
void Lock(Type* data, void* key)
{
if (!pKey)
{
pKey = key;
pData = data;
}
}
Type* Unlock(void* key) const
{
if (key == pKey)
return pData;
}
Type* operator->()
{
return pData;
}
private:
Type* pData = nullptr;
void* pKey = nullptr;
};
template<class Type>
class SafePtrArray {
public:
SafePtrArray() {}
~SafePtrArray() {}
template<class... Args>
SafePtr<Type> CreatePtr(Args&&... args)
{
Type* data = new Type(args...);
ptrs.insert(ptrs.end(), data);
SafePtr<Type> ptr;
ptr.Lock(data, this);
return ptr;
}
Type* UnlockPtr(const SafePtr<int>& ptr)
{
return ptr.Unlock(this);
}
void Destroy(const SafePtr<int>& ptr)
{
Type* pointer = ptr.Unlock(this);
for (auto itr = ptrs.begin(); itr != ptrs.end(); itr++)
{
if ((*itr) == pointer)
{
delete pointer;
ptrs.erase(itr);
}
}
}
private:
std::vector<Type*> ptrs;
};
The goal is to protect a pointer so that the user can access its members but not get to manipulate its actual pointer (mainly delete it prematurely). And also I need to store all the pointers in an array so that when the parent object destroys, I can automatically destroy all the allocated pointers
For this I use two classes, SafePtr and SafePtrArray. SafePtrArray creates and stores the pointers and wraps them in the SafePtr and returns it to the user. SafePtr is just a wrapper and should not let the user get access to the underlying pointer but will allow them to access its members.
It works fine at first but soon I found this error,
int main()
{
SafePtrArray<int> ptr;
auto pInt = ptr.CreatePtr();
int* i = pInt.operator->(); // Users can get access to the underlying pointer using this.
ptr.Destroy(pInt);
}
Is there a way to prevent users from getting access to the underlying type and prevent them from manipulating the pointer while having the privilege to access its members?
I still think you try to solve a problem that has more to do with possible flaws in the design of the API/of the code, the documentation, or with the lack of C++ knowledge of the one using it, with a "solution" that has more cons than pros.
If a C++ programmer does not know what ownership is or does not respect it and blindly deletes objects or frees the memory of pointers, then there will be much bigger concerns. You likely will move the problem just to a different part of the code.
Having that said, the closest you can do to not expose the pointer right now is something like this:
(The code is just a proof of concept, so things like call might need to be improved)
#include <iostream>
#include <string>
struct Test {
void foo(int x, int y, std::string str) {
std::cout << x << " " << y << " " << str << std::endl;
}
double test = 0.5;
};
template <typename T>
struct Ptr {
template <auto M, typename... Args>
auto call(Args... args) {
return (obj.*M)(std::forward<Args>(args)...);
}
template <auto M>
auto get() {
return (obj.*M);
}
protected:
T obj;
};
int main() {
Ptr<Test> p;
p.call<&Test::foo>(1, 2, "hello");
std::cout << p.get<&Test::test>() << std::endl;
return 0;
}
But I still don't think that this is a good approach.
And a user can still mess around with the code and do something bad like:
int main() {
Ptr<Test> p;
delete &p;
return 0;
}
Or this, which for sure is undefined behavior, but that does not really matter as deleting a not owned object will also result in undefined behavior at some point:
template<typename T>
struct Ptr {
protected:
T *obj;
}
template<typename T>
struct Ptr2 {
public:
T *obj;
};
int main()
{
Ptr<Test> p;
Ptr2<Test> *p2 = reinterpret_cast<Ptr2<Test>*>(&p);
std::cout << p2->obj << std::endl;
}
So there is no protection again such things.
Besides the shown code, there is a proposal for reflection that is feature complete now, which would allow getting information about the members of a type, but this was not added to c++20, and one for metaclasses which is also not in the standard yet.
With these two proposals, you might be able to implement something better useable. But my concerns about the benefits of this remain.
Is there a way to prevent users from getting access to the underlying type and prevent them from manipulating the pointer while having the privilege to access its members?
Under certain conditions, no, this is not possible. If the underlying Type is a standard layout class then providing access to the first non-static non-bitfield data member breaks your goal. (Caveat: providing access to just the value of the member is a different story.) The address of that member can be converted to a pointer to the underlying object via reinterpret_cast, which allows calling delete on that pointer. (Well, "allows" in the sense that the call is syntactically valid. Not much else matters for "allows" since we are headed into undefined behavior anyway.)
For classes that are not standard layout, there are probably compiler-specific (non-portable) methods to achieve the same effect (converting the address of a data member into a pointer to the underlying object). There is no reason for a compiler to try actively to thwart such things.
If a programmer is determined to invoke undefined behavior, there is little you can do to stop it.
Related
I have a ServiceProvider class which contains a couple of pointers to different services, like that:
class ServiceProvider()
{
Service3* GetService3();
public:
void Process(Object* o);
void Shrink();
private:
TAutoSpawningPtr<Service1> service1;
TAutoSpawningPtr<Service2> service2;
Service3* service3;
}
Note that TAutoSpawningPtr is a theoretical smart pointer сlass I'm looking for, and service3 is declared as an ordinary pointer to explicitly show the behaviour I needed.
The body of Process():
void ServiceProvider::Process(Object* o)
{
service1->Process(o);
service2->Process(o);
GetService3()->Process(o);
}
The body of GetService3():
void ServiceProvider::GetService3()
{
if(!service3)
{
service3 = new Service3();
}
return service3;
}
As you can see, an instance of Service3 is being created lazily and it don't exist until it needed.
Shrink() method is being called periodically to delete all internal services. Like this:
void ServiceProvider::Shrink()
{
service1.Release(); // delete its internal Service1 pointer if it exists.
service2.Release(); // delete its internal Service2 pointer if it exists.
if (service3)
{
// delete its internal Service3 pointer if it exists.
delete service3;
service3 = nullptr;
}
}
What do I need: I want TAutoSpawningPtr<> to be a smart pointer class, which automatically creates its class instance by calling the default construcror once I dereference the pointer using an overloaded operator->. An inner resource posessed by the pointer had to be deleted once called the Release() method (and, of course, it had to be recreated when I need it again).
Why do I need this?
To automatically control presence/absence of an object.
To prevent nullptrs when derefenecing pointers directly (like this->service3->Process(o)) instead of indirect GetService3().
To release unused services without explicit checks.
The question is: Does the standard (or any third-party) library have an auto pointer class which will satisfy my needs? And if not, would you kindly to bring me some code examples that shows behavior I need. Thanks.
The simplest solution here would be to just call a function that initializes the two if they are uninitialized or are not pointing to anything.
But if you really want to, you can create a simple proxy pointer class that does this for you. For example
#include <iostream>
#include <memory>
using std::cout;
using std::endl;
class Something {
public:
Something() {
cout << __PRETTY_FUNCTION__ << endl;
}
void do_something() {
cout << __PRETTY_FUNCTION__ << endl;
}
};
template <typename Type,
template <typename...> class Ptr = std::unique_ptr>
class AutoAllocatingPtr {
public:
Type* operator->() {
if (!this->ptr) {
this->ptr = Ptr<Type>{new Type{}};
}
return this->ptr.get();
}
void release() {
this->ptr.reset();
}
private:
Ptr<Type> ptr;
};
int main() {
// default unique ownership with std::unique_ptr
auto ptr = AutoAllocatingPtr<Something>{};
ptr->do_something();
ptr.release();
ptr->do_something();
// if you want shared ownership
auto s_ptr = AutoAllocatingPtr<Something, std::shared_ptr>{};
s_ptr->do_something();
s_ptr.release();
s_ptr->do_something();
}
Note Note the code in the end and how you can use that to switch the type of ownership semantics that the pointer exhibits.
Introduction
I have a data structure : pool of values. (not pool of pointers)
When I called create(), it will return Handle.
Everything is good so far.
template<class T> class Pool{
std::vector<T> v; //store by value
Handle<T> create(){ .... }
}
template<class T> class Handle{
Pool<T>* pool_; //pointer back to container
int pool_index_; //where I am in the container
T* operator->() {
return pool_->v.at(pool_index_); //i.e. "pool[index]"
}
void destroy(){
pool_-> ... destroy(this) .... mark "pool_index_" as unused, etc ....
}
}
Now I want Handle<> to support polymorphism.
Question
Many experts have kindly advised me to use weak_ptr, but I still have been left in blank for a week, don't know how to do it.
The major parts that I stuck are :-
Should create() return weak_ptr, not Handle?
.... or should Handle encapsulate weak_ptr?
If create() return weak_ptr for user's program, ...
how weak_ptr would know pool_index_? It doesn't have such field.
If the user cast weak_ptr/Handle to a parent class pointer as followed, there are many issues :-
e.g.
class B{}
class C : public B { ......
}
....
{
Pool<C> cs;
Handle<C> cPtr=cs.create();
Handle<B> bPtr=cPtr; // casting ;expected to be valid,
// ... but how? (weak_ptr may solve it)
bPtr->destroy() ; // aPtr will invoke Pool<B>::destroy which is wrong!
// Pool<C>::destroy is the correct one
bPtr.operator->() ; // face the same problem as above
}
Assumption
Pool is always deleted after Handle (for simplicity).
no multi-threading
Here are similar questions, but none are close enough.
C++ object-pool that provides items as smart-pointers that are returned to pool upon deletion
C++11 memory pool design pattern?
Regarding weak_ptr
A std::weak_ptr is always associated with a std::shared_ptr. To use weak_ptr you would have to manage your objects with shared_ptr. This would mean ownership of your objects can be shared: Anybody can construct a shared_ptr from a weak_ptr and store it somewhere. The pointed-to object will only get deleted when all shared_ptr's are destroyed. The Pool will lose direct control over object deallocation and thus cannot support a public destroy() function.
With shared ownership things can get really messy.
This is one reason why std::unique_ptr often is a better alternative for object lifetime management (sadly it doesn't work with weak_ptr). Your Handle::destroy() function also implies that this is not what you want and that the Pool alone should handle the lifetime of its objects.
However, shared_ptr/weak_ptr are designed for multi-threaded applications. In a single-threaded environment you can get weak_ptr-like functionality (check for valid targets and avoid dangling pointers) without using weak_ptr at all:
template<class T> class Pool {
bool isAlive(int index) const { ... }
}
template<class T> class Handle {
explicit operator bool() const { return pool_->isAlive(pool_index_); }
}
Why does this only work in a single-threaded environment?
Consider this scenario in a multi-threaded program:
void doSomething(std::weak_ptr<Obj> weak) {
std::shared_ptr<Obj> shared = weak.lock();
if(shared) {
// Another thread might destroy the object right here
// if we didn't have our own shared_ptr<Obj>
shared->doIt(); // And this would crash
}
}
In the above case, we have to make sure that the pointed-to object is still accessible after the if(). We therefore construct a shared_ptr that will keep it alive - no matter what.
In a single-threaded program you don't have to worry about that:
void doSomething(Handle<Obj> handle) {
if(handle) {
// No other threads can interfere
handle->doIt();
}
}
You still have to be careful when dereferencing the handle multiple times. Example:
void doDamage(Handle<GameUnit> source, Handle<GameUnit> target) {
if(source && target) {
source->invokeAction(target);
// What if 'target' reflects some damage back and kills 'source'?
source->payMana(); // Segfault
}
}
But with another if(source) you can now easily check if the handle is still valid!
Casting Handles
So, the template argument T as in Handle<T> doesn't necessarily match the type of the pool. Maybe you could resolve this with template magic. I can only come up with a solution that uses dynamic dispatch (virtual method calls):
struct PoolBase {
virtual void destroy(int index) = 0;
virtual void* get(int index) = 0;
virtual bool isAlive(int index) const = 0;
};
template<class T> struct Pool : public PoolBase {
Handle<T> create() { return Handle<T>(this, nextIndex); }
void destroy(int index) override { ... }
void* get(int index) override { ... }
bool isAlive(int index) const override { ... }
};
template<class T> struct Handle {
PoolBase* pool_;
int pool_index_;
Handle(PoolBase* pool, int index) : pool_(pool), pool_index_(index) {}
// Conversion Constructor
template<class D> Handle(const Handle<D>& orig) {
T* Cannot_cast_Handle = (D*)nullptr;
(void)Cannot_cast_Handle;
pool_ = orig.pool_;
pool_index_ = orig.pool_index_;
}
explicit operator bool() const { return pool_->isAlive(pool_index_); }
T* operator->() { return static_cast<T*>( pool_->get(pool_index_) ); }
void destroy() { pool_->destroy(pool_index_); }
};
Usage:
Pool<Impl> pool;
Handle<Impl> impl = pool.create();
// Conversions
Handle<Base> base = impl; // Works
Handle<Impl> impl2 = base; // Compile error - which is expected
The lines that check for valid conversions are likely to be optimized out. The check will still happen at compile-time! Trying an invalid conversion will give you an error like this:
error: invalid conversion from 'Base*' to 'Impl*' [-fpermissive]
T* Cannot_cast_Handle = (D*)nullptr;
I uploaded a simple, compilable test case here: http://ideone.com/xeEdj5
I am a bit embarrassed of asking such a simple question:
Is there any pointer class in cpp that initializes itself with nullptr but is 100% compatible to a basic c-stylish pointer?
to write:
extern "C" void someFunction(const Struct* i_s);
std::ptr<Struct> p;
// ...
p = new Struct;
// ...
someFunction(p);
Is there such a thing?
Or maybe in boost or Qt?
Edit: to make it clear: iam not searching for a smart pointer that takes ownership of the pointer and does ref counting.
You can use the following syntax
std::unique_ptr<Struct> up{};
(or std::shared_ptr). This way, the pointer is value-initialized, i.e. nullptr is being assigned to it.
See http://en.cppreference.com/w/cpp/memory/unique_ptr/unique_ptr for details about the default constructor.
If you looking for a "smart" pointer that just initialized by default with nullptr, then you can write a wrapper. A very basic version below:
#include <iostream>
template <typename T>
struct safe_ptr
{
T* _ptr;
explicit safe_ptr(T* ptr = nullptr):_ptr{ptr}{}
operator T*() const {return _ptr;}
safe_ptr& operator=(T* rhs)
{
_ptr = rhs;
return *this;
}
};
void test(int* p){}
int main()
{
safe_ptr<int> s;
if(s==nullptr)
std::cout << "Yes, we are safe!" << std::endl;
// test that it "decays"
test(s);
s = new int[10]; // can assign
delete[] s; // can delete
}
There is no such thing in C++ since all of the special pointer classes implement some form of ownership other than "maintained by someone else". You could technically use shared_ptr with an empty deleter but that adds reference counting you don't actually need.
The correct C++ solution is to just always add = 0; or = nullptr; to your raw pointer declarations that aren't initialized at declaration.
All that said, this question is tagged just as C++ so the idiomatic answer is to not use raw pointers in your code (except for non-owning cases obviously).
100% compatible to a basic c-stylish pointer
std::unique_ptr and std::shared_ptr do not have automatic conversions to a raw pointer, and that's a good thing as it would inevitably lead to horrible bugs. They take ownership, and in your comments you explicitly say:
the pointer should not take ownership of the given Pointer.
If you insist, you can define a "smart" pointer class yourself:
template <class T>
class RawPointer final
{
private:
T* raw_ptr;
public:
RawPointer(T* raw_tr) : raw_ptr(raw_ptr) {}
RawPointer() : raw_ptr(nullptr) {}
operator T*() const { return raw_ptr; }
};
struct Struct
{
};
void someFunction(const Struct* i_s);
int main()
{
RawPointer<Struct> p;
someFunction(p);
}
Is this a good idea? Probably not. You should just get into the habit of initializing your raw pointers:
Struct* p = nullptr;
On the other hand, people are thinking about a very similar addition to the standard library in the future. You may find A Proposal for the World’s Dumbest Smart Pointer an interesting read.
If this is really the behavior that you want, it would be trivial to implement it yourself in a template. Here's one such implementation:
template<class T>
class ptr_t{
T* ptr;
public:
ptr_t() : ptr(nullptr){ }
ptr_t(const ptr_t& other) : ptr(other.ptr){ }
ptr_t(T* other) : ptr(other){ }
T& operator*(){
return *ptr;
}
T* operator->(){
return ptr;
}
template<class U>
operator U(){
return (U)ptr;
}
}
However, the amount of convenience you will gain from such a device will be rather limited. You're probably much better off taking another approach.
Suppose there's API like below:
typedef void callback_t(void* data);
void addCallback(handle_t h, callback_t callback, void* data);
I'd like to wrap this API to a higher order C++ interface:
template<class F, bool emplace = IsEmplaceable<F>::value>
struct MakeCallback;
class Handle
{
template<class F>
void addCallback(F f)
{
::addCallback(_h, MakeCallback<F>::f, MakeCallback<F>::create(f));
}
handle_t _h;
};
so that the user can pass any callable object (e.g. lambda function).
I'd like to apply small object optimization to avoid dynamic alloc (e.g. for empty lambdas), the trait IsEmplaceable<F> decides whether F can be emplaced in a void*.
For F that is not emplaceable, MakeCallback can be implemented like below:
template<class F>
struct MakeCallback<F, false>
{
static void f(void* data)
{
auto f = static_cast<F*>(data);
(*f)(status);
delete f;
}
static void* create(F& f)
{
return new F(std::move(f));
}
};
For F that is emplaceable, how could I properly implement the following?
template<class F>
struct MakeCallback<F, true>
{
static void f(void* data)
{
// from void* to F
}
static void* create(F& f)
{
// form F to void*
}
};
More basically, can a void* hold a non-address value if we don't use it as a pointer? will it be UB?
A very big warning should be mentioned before even attempting the code shown in this answer. Doing this is most likely very very undefined and not portable behavior. I would highly suggest not doing this as it could very well break a long time into the future and you will have a very hard time finding out why.
That being said, it appears to work on at least my compiler. Results may vary for other compilers. I use a union to convert between a class instance and a void *, don't know of any other clean way to do this. This should work as long as sizeof( Class ) <= sizeof( void * ), but I make no guarantees on behavior with different compilers or even with the exact same compiler I used on my exact same setup.
#include <iostream>
using namespace std;
class Small {
public:
int i;
};
void *castToVoid( Small& s ) {
union {
Small s;
void *p;
} un;
un.s = s;
return un.p;
}
Small castToSmall( void *p ) {
union {
Small s;
void *p;
} un;
un.p = p;
return un.s;
}
int main( ) {
Small s;
s.i = 100;
void *p = castToVoid( s );
s.i = 200;
cout << p << endl; // Prints 0x64
Small s2 = castToSmall( p );
cout << s2.i << endl; // Prints 100
}
or this example for converting to/from a void *
void *castToVoid( Small& s ) {
void **p = reinterpret_cast< void ** >( &s );
return *p;
}
Small castToSmall( void *p ) {
Small *s = reinterpret_cast< Small * >( &p );
return *s;
}
It's implementation-defined behavior according to the C++ standard (draft N3797).
§ 3.7.4.2/p4
Indirection through an invalid pointer value and passing an invalid
pointer value to a deallocation function have undefined behavior. Any
other use of an invalid pointer value has implementation-defined
behavior.
footnote 38:
Some implementations might define that copying an invalid pointer
value causes a system-generated runtime fault
§ 3.7.4.3/p4
An implementation may have relaxed pointer safety, in which case the
validity of a pointer value does not depend on whether it is a
safely-derived pointer value. Alternatively, an implementation may
have strict pointer safety, in which case a pointer value referring to
an object with dynamic storage duration that is not a safely-derived
pointer value is an invalid pointer value unless the referenced
complete object has previously been declared reachable (20.7.4) [...] It is implementation
defined whether an implementation has relaxed or strict pointer safety.
(emphasis mine)
So it is safe if the implementation has relaxed pointer safety, and we can use the union trick as shown in the answer from #Smith_61 to avoid strict aliasing.
Is it possible to maintain knowledge of the derived class in any std c++ container without using pointers, dynamically casting return values from the container? I know I can create a vector or what ever of pointers of some base class type, and have them retain their sub classes. But the question is do I have to use pointers?
Example:
struct A {
int x = 0, y = 0, z = 0;
virtual void foo() { cout << "A" << endl; };
};
struct B : public A {
int a = 1, b = 1, c = 1;
virtual void foo() { cout << "B" << endl; };
};
int main() {
<SOMECONTAINER><A> a(2);
a[0] = A();
a[1] = B();
B * p;
B& n = dynamic_cast<B&>(a[1]); // Always throws?
p = dynamic_cast<B*>(&a[1]); // Always zero?
cout << p << endl;
}
Yes, you do have to use pointers. Otherwise, attempting to put a B into a container of A results in slicing: the B gets cut down into an A (this is not limited to containers, the exact same thing happens if you do A a = B() or if you pass a B to a function expecting an A).
When you later take it back out, it's an A that has absolutely no knowledge its lineage includes an illustrious forefather of type B -- and no matter what way you look at an A, you can't make it a B.
I am going to ignore alignment, or rather assume that data after a pointer is sufficiently aligned.
template<class T, unsigned N>
struct poly_anna;
template<class T,unsigned N>
struct poly_bob {
typedef poly_anna<T,N> poly_anna_;
T*(*get)(poly_anna_*) = nullptr;
void(*destroy)(poly_anna_*) = nullptr;
void(*move_to)(poly_anna_ *,poly_anna_*) = nullptr;
void(*copy_to)(poly_anna_ const*, poly_anna_*)=nullptr;
};
template<class T, unsigned N>
struct poly_anna {
private:
poly_bob<T,N> const*bob=nullptr;
char buff[N];
public:
template<class U> static poly_bob<T,N> const* get_bob() {
static poly_bob<T,N> b={
[](poly_anna*a)->T&{ return *(U*)&a->buff[0]; },
[](poly_anna*a){ ((U*)&a->buff[0])->~U(); a->bob = nullptr; },
[](poly_anna*s,poly_anna*d){
if (s->bob==d->bob){
*((U*)&d->buff[0])=std::move(*((U*)&d->buff[0]));
return;
}
if (d->bob != nullptr) {
d->bob->destroy(b);
}
d->store( std::move( *(U*)&s->buff[0] ) );
},
[](poly_anna const* s, poly_anna*d){
if (d->bob == s->bob){
*(U*)&d->buff[0] = *(U const*)&s->buff[0];
return;
}
if (d->bob){ d->bob->destroy(d); }
d->store( *(U const*)*s->buff[0] );
}
};
return &b;
};
template<class U_>
void store(U_&& u){
typedef typename std::decay<U_>::type U;
static_assert( sizeof(U)<=N, "N not large enough" );
if (bob) bob->destroy( this );
bob = get_bob<U>();
new (&buff[0]) U( std::forward<U_>(u) );
}
void reset(){ if (bob) bob->destroy(this); }
T& get() {
return bob->get(this);
}
T const& get() const {
return bob->get(const_cast<poly_anna*>(this));
}
poly_anna( poly_anna const& o ){
if (o.bob) o.bob->copy_to( &o, this );
}
poly_anna( poly_anna && o ){
if (o.bob) o.bob->move_to( &o, this );
}
poly_anna&operator=( poly_anna const& o ){
if (o.bob) o.bob->copy_to( &o, this );
else if (bob) bob->destroy(this);
return *this
}
poly_anna&operator=( poly_anna && o ){
if (o.bob) o.bob->move_to( &o, this );
else if (bob) bob->destroy(this);
return *this
}
poly_anna()=default;
~poly_anna(){if(bob)bob->destroy(this);}
explicit operator bool()const{return bob;}
};
That is my attempt at a polymorphic variant. It stores T and children of T so long as they are no larger than N and can be stored in std containers.
Let me know if it compiles.
You need pointers for virtual member function dispatch.
When you think about it, without pointers, you are left with "by value". Value semantics and and polymorphism don't really make sense together.
A value has a single context / type. It is atomic and simple. WYSIWIG, so to speak. Sure, you can cast it, but then you have ... another value.
There's an oft-quoted programmer proverb: There is no problem which cannot be solved with an additional layer of indirection, except too many layers of indirection.
Putting it into practice, take a look at boost::variant.
If your container stores boost::variants allowing all the (sub-)classes you want to store, you can avoid pointers.
That can be a win, but need not be.
Measure before you commit to such a solution.
I think there are actually two questions here:
Is it possible to get polymorphic semantics in an STL container without using pointers and the associated dynamic allocation?
Is is possible to retain the concrete type of a polymorphic object stored in an STL container?
The answer to 1 is yes, with some effort. As some have mentioned, one way to do this is to use a variant type like boost::variant. The problem with that approach is that you lose the ability to interact naturally with the objects stored in the variant and instead have to write visitors, which have a lot of syntactic overhead.
If the class hierarchy is bounded then a better approach might be to use a variation on boost::variant (no pun intended) specifically designed to preserve polymorphic semantics and its associated syntax. One example might be the emplacer. As noted in dyp's comment above, emplacer is a restricted variant.
As for question 2, I'm not aware of any way to do that without using typeid() or a hand-rolled type system.