简体   繁体   English

模板类中非模板方法的模板专业化

[英]Template specialization on a non template method in a template class

It is possible to use template specialization to achieve stuff like this: 可以使用模板专门化来实现以下目的:

template <typename T>
T bar(T baz);

template <>
static unsigned int bar<unsigned int>(unsigned int baz)
{
    return baz + 1;
}

template <>
static int bar<int>(int baz)
{
    return baz + 2;
}

But what if the template parameters are on a class that contains the method? 但是,如果模板参数在包含该方法的类上,该怎么办?

template <typename T>
class Foo
{
    T fooBar(T baz);
};

How can I (if at all) use template specialization to implement different forms of the fooBar method like I did above? 我怎么能(如果有的话)使用模板专门化来实现fooBar方法的不同形式,就像我上面做的那样?

Thanks 谢谢

The same basic way, you just have to make it clear where the template is. 同样的基本方法,你只需要明确模板的位置。

This would be wrong , because while the method is implicitly a template (because the class is) it "inherits" the template types from the class: 这将是错误的 ,因为虽然该方法隐式是模板(因为类是),但它“继承”了该类的模板类型:

template <>
inline unsigned int Foo::fooBar<unsigned int>(unsigned int baz)

So instead, specify the type after the class: 因此,请在类之后指定类型:

template <>
inline unsigned int Foo<unsigned int>::fooBar(unsigned int baz)
{
    return baz + 1;
}

template <>
inline int Foo<int>::fooBar(int baz)
{
    return baz + 2;
}

( Demo ) 演示

Note that inline is required here since these are not template functions, but rather are specializations. 请注意,此处需要inline ,因为它们不是模板函数,而是专业化。 Therefore, they must follow the One Definition Rule. 因此,他们必须遵循一个定义规则。 inline suppresses the ODR as with any other non-template function/method definition. 与任何其他非模板函数/方法定义一样, inline抑制ODR。

Alternatively, you could declare them in the header and implement them in an implementation file: 或者,您可以在标头中声明它们并在实现文件中实现它们:

// Header file
template <>
unsigned int Foo<unsigned int>::fooBar(unsigned int baz);

template <>
int Foo<int>::fooBar(int baz);

// Implementation file
template <>
unsigned int Foo<unsigned int>::fooBar(unsigned int baz)
{
    return baz + 1;
}

template <>
int Foo<int>::fooBar(int baz)
{
    return baz + 2;
}

The same basic syntax applies to template methods in template types, except you need two template <> since you are specializing two different levels of templates: 相同的基本语法适用于模板类型中的模板方法,除了您需要两个template <>因为您要专门化两个不同级别的模板:

template <typename T>
class Foo
{
public:
    template <typename U>
    void foobar(T t, U u);
};

// Specialization of T=int, U=unsigned int
template <>
template <>
inline void Foo<int>::foobar<unsigned int>(int t, unsigned int u)
{
    // ...
}

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

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