我将尝试通过一个简单的例子来解释我的问题:
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>
该类,则在所有其他情况下,该程序都无需编译。
我能怎么做?
您可能会static_assert
遇到以下情况(具有特质std::is_base_of
):
template<class RUNNABLE>
class Task : public RUNNABLE
{
public:
static_assert(std::is_base_of<Runnable, RUNNABLE>::value
&& !std::is_same<Runnable , RUNNABLE>::value);
// ...
};
好的,很好的解决方案,我稍微修改了我的初始问题,使
Runnable
该类不再是抽象的。std::is_base_of<Runnable , Runnable >::value
是真的。如果您担心的话。但我希望它返回假
您仍然可以添加和
&& !std::is_same<Runnable , RUNNABLE>::value
。