简体   繁体   English

C ++中的模板专业化

[英]template specialization in C++

I've been trying to understand template specializations. 我一直在努力理解模板专业化。 Why is this generating an error ( specialization of 'T foo(T, T) [with T = int]' after instantiation ) 为什么会产生错误( specialization of 'T foo(T, T) [with T = int]' after instantiation

template <class T> T foo(T a, T b);

int main()
{
    int x=34, y=54;
    cout<<foo(x, y);
}

template <class T> T foo(T a, T b)
{
    return a+b;
}

template <> int foo<int>(int a, int b)
{
    cout<<"int specialization";
}

The standard demands that all template definitions must be known at the time of instantiation, and that every translation unit see the same definition. 该标准要求在实例化时必须知道所有模板定义,并且每个翻译单元都看到相同的定义。 Otherwise your program is ill-formed (and in fact no diagnostic is required). 否则您的程序格式不正确(实际上不需要诊断)。

(So to solve this, just put all the template definitions at the top of the program.) (所以要解决这个问题,只需将所有模板定义放在程序的顶部。)

Remember that template functions aren't functions, just templates. 请记住,模板函数不是函数,只是模板。 Think of them as a code generation tool. 将它们视为代码生成工具。

The explicitly specialized template function foo() should be visible before it can be called/Instantiated. 显式专用模板函数foo()在被调用/实例化之前应该是可见的。

In fact the above rule applies to all Template functions. 实际上,上述规则适用于所有模板功能。

Solution: 解:
Move the template specialization for foo() before your main() . main()之前移动foo()的模板特化。

Following should work just fine: 以下应该工作得很好:

template <class T> T foo(T a, T b);

/*Should be visible before instantiation*/
template <> int foo<int>(int a, int b)
{
    cout<<"int specialization";
}

int main()
{
    int x=34, y=54;
    cout<<foo(x, y);
}

template <class T> T foo(T a, T b)
{
    return a+b;
}

Don't do that. 不要那样做。

What Herb Sutter said: Herb Sutter说:

If you're writing a function base template, prefer to write it as a single function template that should never be specialized or overloaded, and then implement the function template entirely as a simple handoff to a class template containing a static function with the same signature. 如果你正在编写一个函数库模板,宁愿把它写成一个永远不应该专门化或重载的单个函数模板,然后完全实现函数模板作为包含具有相同签名的静态函数的类模板的简单切换。

See: http://www.gotw.ca/publications/mill17.htm 见: http//www.gotw.ca/publications/mill17.htm

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

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