Search code examples
c++11functorstatic-cast

How do I pass static_cast<T> as a function?


I have a type A that's designed to be implicitly casted to type B. Here's an example case I'd like to use it in:

// Current implementation:
std::transform(vec_of_a.begin(), vec_of_a.end(), std::back_inserter(vec_of_b),
               [](const A& a) -> B { return a; });  // Thanks, Kerrek SB.

// Ideal implementation - Won't compile, expected '(' after 'static_cast'.
std::transform(vec_of_a.begin(), vec_of_a.end(), std::back_inserter(vec_of_b),
               static_cast<B>);

What can I do to make the latter option compile?


Solution

  • static_cast<B>, while it is invoked with function-call syntax cannot be passed like other callable things. E.g., there's no way to use & to get a function pointer to it.

    You can use a short little lambda to achieve something similar to passing a function pointer to static_cast<B>, as you do in your current implementation:

    std::transform(vec_of_a.begin(), vec_of_a.end(), std::back_inserter(vec_of_b),
                   [](const A& a) -> B { return a; });
    

    Another option--in this particular case--would be to construct a vector<B> from the vector<A>:

    std::vector<B> vec_of_b(vec_of_a.begin(), vec_of_a.end());
    

    (This answer is a summary of the comments on both the question and bipll's answer.)