Solved

Posted on 2013-12-18

Suppose I write a generic function to calculate the square of a number

```
template<class T> T square(const T & in)
{
return in*in;
}
```

and I have a vector of integers called v. When I try to run the following code, I get an error:```
std::vector<int> v2;
std::transform(v.begin(), v.end(), std::back_inserter(v2), square);
```

I get an error. However, if I create the following struct```
struct squareTempl
{
template< typename T >
T operator ()(const T& in) const {return in*in;}
};
```

then I can use```
std::transform(v.begin(), v.end(), std::back_inserter(v2), squareTempl());
```

without any problems. Why is there such a discrepancy?
3 Comments

std::vector<int> v2;

std::transform(v.begin(), v.end(), std::back_inserter(v2), square<int>);

Notice that I am explicitly instantiating the template function for type int.

Put another way "square" is not a concrete function but "square<int>" is.

squareTempl *is* a concrete object.

Title | # Comments | Views | Activity |
---|---|---|---|

Connecting to MS SQL db from Win32 application written in C | 3 | 71 | |

Retrieve PID of MicrosoftEdge.exe with GetForegroundWindow() | 6 | 111 | |

Template syntax for variable length arrays | 9 | 65 | |

trigs fail! I thought I knew how to do trignometry | 3 | 19 |

Join the community of 500,000 technology professionals and ask your questions.

Connect with top rated Experts

**11** Experts available now in Live!