1

There is something that has been on my mind for a long time now. Just consider this function:

template<typename T>
T foo(const T& value)
{
    return value;
}

It's the simplest possible function wrapper for any given value. However, I've been wondering whether it has a "standard name" (that many would recognize, like functions such as map, filter, sqrt, etc...). And are they well-known problems that require to use such a function?

Morwenn
  • 21,684
  • 12
  • 93
  • 152
  • 1
    Here are good examples on using id function on [Haskell]. I know this is for C++, but the examples there on where and when use id function are really good: http://stackoverflow.com/questions/3136338/uses-for-haskell-id-function – hectorg87 Jul 18 '12 at 09:00
  • @hectorg87 Nice examples, I think I can see part of it usefulness in functional programming. Thanks! – Morwenn Jul 18 '12 at 09:06
  • you are welcome. Since you have higher order functions in C++ too, it's not crazy to think you could use identity this way too, however **I think** that it's not the most common way to code in C++. – hectorg87 Jul 18 '12 at 09:12
  • Yeah, C++ allows functional programming, but it's not the main paradigm C++ was designed for. It's probably more useful in LISP dialects and siblings. – Morwenn Jul 18 '12 at 09:20

4 Answers4

7

In principle it's an identity function, but in practice it forces a copy of the argument.

So, if T has value semantics, it's still a real identity. Otherwise, it's a cloning function.

A perfect identity would be

template<typename T>
const T& identity(const T& value)
{
    return value;
}
Luc Touraille
  • 79,925
  • 15
  • 92
  • 137
Useless
  • 64,155
  • 6
  • 88
  • 132
2

It's an identity function. It's useful, for example, for when you have to pass a projection to some other function and don't want any projection. No, not terribly useful, but that's the best you can get from a function that basically does nothing.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
2

Without any changes to the parameter inside the function, I'm not sure it has any programming nomenclature.

You also can't say it's a full-on identity as the object returned isn't the same object, since you return by value.

I'd say it's a cloning function.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

Here's an explanation for identity functions

YePhIcK
  • 5,816
  • 2
  • 27
  • 52
  • 1
    For reference, SO usually prefers answers to be somewhat self-contained (athough links to references are naturally welcome). Reference on [meta](http://meta.stackexchange.com/q/8231). It wasn't my downvote btw, but I thought you'd like to know. – Useless Jul 18 '12 at 14:59