Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I've implemented an identity function (well, actually a functor struct) in C++. The goal is that every occurrence of an expression expr in the code can be substituted by identity(expr) without changing the semantics of the program at all.

I make it a struct with a templated operator() instead of simply a function template because this enables us to pass identity as an argument to other functions (say std::transform) without needing to specify the type (e.g., identity<std::pair<std::vector<int>::const_iterator, std::vector<double>::const_iterator>>).

The code is written in C++14.

#include <utility>

static constexpr struct identity_t {
    template<typename T>
    constexpr decltype(auto) operator()(T&& t) const noexcept
    {
        return std::forward<T>(t);
    }
} identity{};

Usage:

int x = 42;
identity(x) = 24;

constexpr int size = 123;
int arr[identity(size)] = {};

vector<int> v1 = {1, 2, 3, 4}, v2;
v2.reserve(v1.size());
transform(v1.cbegin(), v1.cend(),
          back_inserter(v2),
          identity);

template<typename T>
class my_container {
public:
    template<typename F>
    auto flat_map(F&& f) const { ... }

    auto flatten() const { return flat_map(identity); }

    ...
};

Since identity(expr) is nothing more than a cast, performance should not be a problem. I'm concerned whether there are cases in which this implementation fails to keep the program's behavior unchanged. If there are, how can I fix the implementation?

EDIT: I changed "a variable x" in the first paragraph to "an expression expr". The latter is more accurate.

share|improve this question
2  
Those ...'s in your code suggest that there is more to your implementation, which you need to include. Right now this question is off topic as it is basically stub code. – syb0rg Jul 12 '16 at 12:42
    
@syb0rg No, the ... is not part of my implementation. That's part of the examples which is not relevant to the discussion. The full implementation is in the first code block. – Zizheng Tai Jul 12 '16 at 12:43
1  
Does it work as intended even without the examples (those cut away with the ...)? – Mast Jul 12 '16 at 12:56
    
@Mast I'm not exactly sure what you mean; identity itself does work. – Zizheng Tai Jul 12 '16 at 12:57
    
@syb0rg I'm new to Code Review, so I don't know if I should remove incomplete examples. Please let me know if I should so I can edit the post accordingly. – Zizheng Tai Jul 12 '16 at 12:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.