I'm searching for a way to only instantiate a class if a condition on the template type is met. I would like to do this within the class during run-/ and compile-time and not terminate the program, but throw an exception.
I'm working on a class where the template type needs to have a time component. Ideally, the type is derived from a class that only defines the time as a member. That way, doing something like the following should be safe:
#include <type_traits>
#include <stdexcept>
class Time
{
public:
double t;
};
class A : Time
{
};
template<class T>
class B
{
T data;
void do_someting()
{
data.t = 12.34;
}
};
B<A> some_instance;
I found this C++ templates that accept only certain types
So the following would do the check, but static_assert only checks during compile time.
template<class T>
class B
{
static_assert(std::is_base_of<Time, T>::value, "T must inherit from Time Class");
T data;
void do_someting()
{
data.t = 12.34;
}
};
Would it be safe to do the following or is there a cleaner way of archiving this?
Edit: Changed due to Timos input.
template<class T>
class B
{
B()
{
if(std::is_base_of<Time, T>::value)
{
throw std::invalid_argument( "T must inherit from Time Class" );
}
}
T data;
void do_someting()
{
data.t = 12.34;
}
};