I’m trying to use the following code, but can’t get it to complete.
Can anyone see the problem?
class IResourceJob
{
public:
virtual ~IResourceJob() {}
virtual void execute() = 0;
};
template<typename T>
class ResourceJob : public IResourceJob
{
public:
void execute()
{
static_assert(false, "Specialised ResourceJob<T> not defined!");
}
};
template<>
class ResourceJob<int>
{
public:
void execute()
{
// test.
}
};
The following usage gives a compile error:
IResourceJob* job = new ResourceJob<int>;
Thanks!
The compiler gives an error for any template that can never be instantiated. For your member function of the class template (i assume you mean
static_assert), that is true, so the compiler is in right to give you a diagnostic.You want to make the condition depend on
Tand cleverly make it always evaluate to false when instantiated. For example likeSince the compiler cannot know whether the user will put a specialization of
always_false(which you won’t, of course), it cannot early-reject the template anymore.I also doubt that you wanted to put the static_assert into
execute, since your error message indicates thatResourceJobas a whole needs to be specialized. So put thestatic_assertoutside of the member function into the class body. If you don’t want the user to specialize the whole template, but only the member function, the user instead needs to sayThis will provide an alternative definition of
executewhich will be used by the template ifTisint.