简体   繁体   English

c ++类模板(默认)

[英]c++ class templating ( with defaults )

I am trying to do something like this. 我正在尝试做这样的事情。 but cannot figure out the right syntax .. any help would be greatly appreciated 但无法找出正确的语法..任何帮助将不胜感激

template <typename T, typename K = UINT32>
class info
{
   K* asArray();
}

template <typename T, typename K = UINT32>
K* info<T, UINT32>:: asArray() { // return a int array };

template <typename T, char>
char* info<T, char>:: asArray() { // return a char array };

This is all you need - put the definition into the class template. 这就是您所需要的-将定义放入类模板。

template <typename T, typename K = int>
class info {
  K* asArray(){ return 0; }
};

A specialisation of the class member alone is possible via eg 例如,可以通过以下方式单独对类成员进行专业化处理:

template<>
char* info<int,char>::asArray(){ return new char[10]; }

This overrides the basic definition in the class template: 这将覆盖类模板中的基本定义:

info<int,char> iv;
char* iptr = iv.asArray();
if( iptr != 0 ) std::cout << "ok - not null" << std::endl;

Displays ok - not null . 显示ok - not null

You cannot have a partial specialization of a member function only. 您不能仅对成员函数进行部分专业化。 You have to create a specialization of the class itself. 您必须创建类本身的特殊化。

template <typename T>
class info<T, char>
{
   char* asArray();
};

Then, you can use: 然后,您可以使用:

template <typename T>
char* info<T, char> asArray  { // return a char array }

This is not allowed: 这是不允许的:

template <typename T, typename K = UINT32>
K* info<T, UINT32>:: asArray() { // return a int array };

You have to use: 您必须使用:

template <typename T, typename K>
K* info<T, K>:: asArray() { // return a K array };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM