I will try to explain my problem with a simple example:
class Runnable
{
protected:
virtual bool Run() { return true; };
};
class MyRunnable : Runnable
{
protected:
bool Run()
{
//...
return true;
}
};
class NotRunnable
{ };
class FakeRunnable
{
protected:
bool Run()
{
//...
return true;
}
};
//RUNNABLE must derive from Runnable
template<class RUNNABLE>
class Task : public RUNNABLE
{
public:
template<class ...Args>
Task(Args... args) : RUNNABLE(forward<Args>(args)...)
{ }
void Start()
{
if(Run()) { //... }
}
};
typedef function<bool()> Run;
template<>
class Task<Run>
{
public:
Task(Run run) : run(run)
{ }
void Start()
{
if(run()) { //... }
}
private:
Run run;
};
main.cpp
Task<MyRunnable>(); //OK: compile
Task<Run>([]() { return true; }); //OK: compile
Task<NotRunnable>(); //OK: not compile
Task<FakeRunnable>(); //Wrong: because compile
Task<Runnable>(); //Wrong: because compile
In summary, if the T template derive from the Runnable class, I want the class Task : public RUNNABLE class to be used. If the template T is of the Run type I want the class Task<Run> class to be used, and in all other cases the program does not have to compile.
How can I do?
You might
static_assertyour condition (with traitsstd::is_base_of):Demo