我将尝试用一个简单的例子来解释我的问题:
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;
};
主文件
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
总之,如果T
模板从Runnable
类派生,我希望使用class Task : public RUNNABLE
该类。如果模板T
是Run
我希望使用的class Task<Run>
类的类型,并且在所有其他情况下,程序不必编译。
我能怎么做?