我正在尝试使用以下代码,但无法完成。
谁能看出问题所在?
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.
}
};
以下用法会产生编译错误:
IResourceJob* job = new ResourceJob<int>;
谢谢!
最佳答案
编译器会为任何无法实例化的模板报错。对于类模板的成员函数(我假设您指的是 static_assert
),这是正确的,因此编译器有权为您提供诊断。
您想使条件依赖于 T
并聪明地让它在实例化时始终评估为 false。比如喜欢
template<typename T>
struct always_false : std::false_type {};
template<typename T>
class ResourceJob : public IResourceJob
{
public:
void execute()
{
static_assert(always_false<T>::value,
"Specialised ResourceJob<T> not defined!");
}
};
由于编译器无法知道用户是否会放置 always_false
的特化(您当然不会),因此它无法再提前拒绝模板。
我也怀疑您是否想将 static_assert 放入 execute
,因为您的错误消息表明 ResourceJob
作为一个整体需要专门化。所以把成员函数外面的static_assert
放到类体中。如果您不希望用户专门化整个模板,而只是成员函数,则用户需要说
// either "inline" and in the header, or not "inline" and in the .cpp file, but then
// put this into the header: template<> void ResourceJob<int>::execute();
template<> inline void ResourceJob<int>::execute() {
}
这将提供 execute
的替代定义,如果 T
是 int
,模板将使用它。
关于c++ - 从模板类派生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11960877/