c++ - 从模板类派生?

标签 c++ templates

我正在尝试使用以下代码,但无法完成。

谁能看出问题所在?

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 的替代定义,如果 Tint,模板将使用它。

关于c++ - 从模板类派生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11960877/

相关文章:

c++ - 无法编译在不同类上调用静态函数的代码

c++ - 多重定义

c++ - 试图在列表上 push_back。 C++

c++ - 使用条件调用模板函数

c++ - 这段代码的目的是什么?

c++ - 为什么命名空间不能是模板参数?

c++ - 在 Windows Vista 上将 MSADO15.DLL 和 C++ 与 MinGW/GCC 结合使用

c++ - 数组中第 k 个最大的元素

c++ - 具有基于 protected 基类方法的返回类型的函数

jquery - 如何将jquery Mustache应用到外部文件/模板