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

时间:2015-10-08 12:16:13

标签: c++ templates

我有一个不是模板但具有模板功能的类,如下所示:

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

我想专门针对一个模板类型说明一个像这样定义的fixed_string:

template <int max>
class fixed_string {
};

我该怎么做?

4 个答案:

答案 0 :(得分:2)

正如@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);

LIVE

答案 1 :(得分:0)

如果我理解你的问题,请这样:

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

答案 2 :(得分:0)

没有部分功能模板专业化,因此,您只能将其专门用于已知最大的fixed_string。

template<>
fixed_string<100> Table::get(int, int)
{
}

答案 3 :(得分:0)

定义:

template<int max>
 fixed_string<max> Get(int, int);

呼叫:

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