【发布时间】:2020-05-16 23:36:20
【问题描述】:
我将尝试用一个简单的例子来解释我的问题:
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
总之,如果T 模板派生自Runnable 类,我希望使用class Task : public RUNNABLE 类。如果模板T 是Run 类型,我希望使用class Task<Run> 类,并且在所有其他情况下程序不必编译。
我该怎么办?
【问题讨论】:
标签: c++ templates inheritance type-constraints template-inheritance