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

时间:2014-04-21 10:41:31

标签: c++

我是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实现中使用的特定变量(在{ {1}}和getPagetoWrite)而不创建类型setPageAsFree的实例。

希望我清楚自己。

2 个答案:

答案 0 :(得分:1)

我不认为可以强制PageType包含特定变量,这在模板实例化期间在编译时很简单 - 你真的不需要任何其他东西。您可以使用C ++ 11 std::is_base_of强制执行static_assertPageType实现了一些可以放置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

答案 1 :(得分:0)

据我所知,你可以使用变量&#39;或功能&#39;应该在您的代码中的名称。像这样:

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

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