1

If I have a class with a unary constructor, can I somehow use that constructor as a UnaryOperator in an algorithm? i.e.:

#include <algorithm>
#include <vector>

class Thing
{
  public:
    Thing(int i)
    : m_i(i)
    {}
    
    int i() {
        return m_i;
    };
    
  private:
    int m_i;
};

int main() {
    std::vector<int> numbers{0,4,-13,99};
    std::vector<Thing> things;
    
    std::transform(numbers.begin(), numbers.end(), std::back_inserter(things), Thing);
}

the above code doesn't work, the code below works but I'm wondering if there's a better way:

#include <algorithm>
#include <vector>

class Thing
{
  public:
    Thing(int i)
    : m_i(i)
    {}

    int i() {
        return m_i;
    };

  private:
    int m_i;
};

int main() {
    std::vector<int> numbers{0,4,-13,99};
    std::vector<Thing> things;

    auto make_thing = [](auto&& i){return Thing(i);};

    std::transform(numbers.begin(), numbers.end(), std::back_inserter(things), make_thing);
}
rbv
  • 363
  • 1
  • 3
  • 15
  • 2
    [possible duplicate](https://stackoverflow.com/questions/44491995/using-class-constructor-as-callable-object) – Drew Dormann Jun 01 '22 at 15:28
  • 1
    You cannot refer to or call a constructor at all (with some exceptions such as `using` declarations). In `Thing(i)`, `Thing` is not the constructor, but the type. It only calls the constructor indirectly. – user17732522 Jun 01 '22 at 16:35

1 Answers1

2

For the first code sample just use a lambda:

    std::transform(numbers.begin(), numbers.end(), std::back_inserter(things), [](int i){ return Thing(i);});

And this is the best way for what your code does. Everybody will understand it.


Constructor can't be used as an UnaryOperator, because it does not return a value.

Sergey Kolesnik
  • 3,009
  • 1
  • 8
  • 28