C++模板:访问模板变量

C++ templates: Accessing template variables

本文关键字:变量 访问 模板 C++      更新时间:2023-10-16

我是C++世界的新手。

我正在尝试使用模板来实现代码。

template<class PageType>
class Book
{
 //implementation
public:
  PageType* FreeQ; //holds the pointers to pages which are yet to be written
  PageType* BusyQ; //holds the pointers to pages which are being written 
  PageType* DoneQ; //holds the pointers to pages which were written
  getPagetoWrite(); //Get from FreeQ and put in BusyQ 
  setPageAsFree();  //Erase data and put in FreeQ
}
//example for PageType implementation
class PlasticType
{
  mutex; // must
  status; // must
  *prev; // must
  *next; // must
  Write( );
  Read();  
}

我想知道是否有任何方法可以通知编译器PageType的实现必须包含将在类Book实现(在getPagetoWritesetPageAsFree中)中使用的特定变量,而不创建类型PageType的实例。

希望我说清楚了。

我不认为强制PageType包含特定变量是可能的,这在模板实例化期间的编译时很简单,您真的不需要其他任何东西。您可以使用C++11 std::is_base_of来使用static_assert强制您的PageType实现一些基类,您可以将getPagetoWrite和setPageAsFree放入其中,但仍然必须实例化您的模板-这是可以的。

#include <type_traits>
class Base {
};
class X : public Base {
};
class Z {
};
template <typename T> 
class Foo {
    static_assert(std::is_base_of<Base,T>::value,"must be derived from Base");
public:
    Foo() {
    }
};
int main(int argc, char** argv) {
    Foo<Z> foo_z_type; // gives compile error: static assertion failed: must be derived from Base
    Foo<X> foo_z_type; // OK
    return 0;
}

http://coliru.stacked-crooked.com/a/bf91079681af3b0e

据我所知,您可以只使用代码中应该存在的变量或函数的名称。像这样:

void getPagetoWrite()
{    
...
//PageType should have a member called pagenum for which operator++ makes sense
BusyQ->pagenum++;
...
}

如果用某个没有pagenum成员的类实例化Book模板,则会出现编译时错误。