简体   繁体   中英

How can I specialize a templates with no-typename argument?

I have this template struct and I need to code different functions for different data types:

template <typename T, int _len>
struct Field {
        T data;
        int len;

        Field(){
            len = _len;
        }
};

How can I specialize it for several types? Something like this:

template <>
void Field<int,int> {
...
    void function() {
    ...
        specialization for int
    ...
    } 
...
};

template <>
void Field<char,int> {
...

    void function() {
    ...
        specialization for char
    ...
    } 
...
};

template <>
void Field<String,int> {
...
    void function() {
    ...
        specialization for String
    ...
    } 
...
};

I accept any type of suggestion, I can even consider using some other type of data structures. I like to use templates to define "Fields" like this:

Field <String, 10> myField

Thanks!!

Specialization is different from inheritance. When you specialize you have to re-declare everything, it is considered a different type.

You can use a base templated struct that contains the common attributes and methods, and then create the template inheriting from it:

#include <iostream>

template<typename T, int _len>
struct FieldBase {
  T data;
  int len;

  FieldBase() {
    len = _len;
  }
};

template<typename T, int _len>
struct Field : public FieldBase<T, _len> {};

template<int _len>
struct Field<int, _len> : public FieldBase<int, _len> {
  void function() {
    std::cout << "int " << this->len << std::endl;
  }
};

template<int _len>
struct Field<char, _len> : public FieldBase<char, _len> {
  void function() {
    std::cout << "char " << this->len << std::endl;
  }
};

int main()
{
  Field<int, 5> f_int;
  Field<char, 10> f_char;

  f_int.function();
  f_char.function();

  return 0;
}

Output:

int 5

char 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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