Specialization of templates in C ++

I tried to understand specialized patterns. Why does this generate an error ( 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"; } 
+4
source share
3 answers

The standard requires that all template definitions be known at the time of instantiation and that each translation unit understands the same definition. Otherwise, your program is poorly formed (and in fact, diagnostics are not required).

(To solve this problem, just put all the template definitions at the top of the program.)

Remember that template functions are not functions, but simply templates. Think of them as a code generation tool.

+8
source

The explicit specialized function of the template foo() must be visible before it can be called / initialized.

In fact, this rule applies to all Template functions.

Decision:
Move the template specialization for foo() to main() .

The following should work 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; } 
+3
source

Do not do this.

What Herb Sutter said:

If you are writing a function base template, prefer to write it as a single function template, which should never be specialized or overloaded, and then fully implement the function template as a simple transfer to a class template containing a static function with the same signature.

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

0
source

Source: https://habr.com/ru/post/1380641/


All Articles