How to detect whether a class T has at least 1 member that are pointers?
#include <iostream>
class B{
int k; //no pointer -> false
};
class C{
void* x; //pointer -> true
};
class D{
int someRandom;
C* aBadPractice; //pointer -> true
};
template<class T> bool hasPointer(){ ??
???
};
int main(){
std::cout<<check<B>()<<std::endl; //false
std::cout<<check<C>()<<std::endl; //true
std::cout<<check<D>()<<std::endl; //true
}
I want to use it to roughly check that every type of component in my Entity-Component-System is a custom POD (plain old data).
If it is violated, it will alert programmer about potential mistake.
I can't use std::is_pod
because its criteria is so much different from mine.
Main objective / criteria :-
- Can be slow (I don't mind performance).
- Compile-time or Runtime check are both OK.
- It must be non-intrusive. (
B
C
&D
should not be edited) - If it helps, it is ok to enforce
B
C
&D
to inherit from a common class.
Side objective :- (not important)
- can detect private field
- detect inherited field
- detect a field that is a type that has pointer inside it
Here are similar questions (they are too different though) :-
- Check if a class has a member function of a given signature : search function with a specific name and signature
- Check if a class has a pointer data member : check whether a field with a certain name is a pointer.
I personally don't think it is possible.
A solution like "It is impossible" is also a valid answer.
Edit
My underlying problem is identifying whether I can memcpy
&& omit destructor of them. I want to relocate them easily and safely - like this : Can I use memcpy in C++ to copy classes that have no pointers or virtual functions.
Now I believe the solution are somethings around std::is_trivially_destructible
and std::is_trivially_copyable
. I will investigate more about them. I hope they can check whether my class contains any smart pointer.
Thank every comments.