如何专门化模板类型的普通类中的模板成员

How to specialize a template member in a normal class for a template type

本文关键字:成员 类型 专门化      更新时间:2023-10-16

我有一个类,它不是模板,但有一个模板函数,如下所示:

class Table {
public:
 template <typename t>
 t Get(int, int);
};

我想对模板类型进行专门化比如像这样定义的fixed_string

template <int max>
class fixed_string {
};

我该怎么做呢?

正如@ForEveR所指出的,没有局部函数模板专门化,您只能为它提供完整的专门化版本。如:

template <>
fixed_string<9> Table::Get<fixed_string<9>>(int, int);
然后用 调用
table.Get<fixed_string<9>>(0, 0);

但是可以重载函数模板,例如:

class Table {
public:
    template <typename t>
    t Get(int, int);
    template <int max>
    fixed_string<max> Get(int, int);
};

Table table;
table.Get<9>(0, 0);

class Table {
public:
    template <typename t>
    t Get(int, int);
    template <int max, template<int> class T=fixed_string>
    T<max> Get(int, int);
};

Table table;
table.Get<9>(0, 0); // or table.Get<9, fixed_string>(0, 0);
生活

如果我理解对了你的问题,像这样:

Table table;
table.Get<fixed_string<100>>(3,4);

没有局部函数模板特化,所以你只能为已知max的fixed_string特化。

template<>
fixed_string<100> Table::get(int, int)
{
}
定义:
template<int max>
 fixed_string<max> Get(int, int);

调用:

Table obj;
fixed_string<20> str = obj.Get<20>(1, 2);