Mike
Mike

Reputation: 702

Using something like auto for initialization

Does something exist in the standard library or language that allows me to avoid having to repeat myself in the following situation? In one case I have to duplicate the type name. In the other, I duplicate the left side. auto is very helpful when doing initialization, but assignment doesn't have such an elegant solution.

std::map<std::string, std::string> howdy;
std::vector<std::pair<std::string, std::string>> there;
howdy = std::map<std::string, std::string>{there.begin(), there.end())};
howdy = decltype(howdy){there.begin(), there.end())};

Something like this does the trick but I would like know if something already exists.

template<typename T, typename... Args>
void assign(T& t, Args&&... args)
{
    t = T{std::forward<Args>(args)...};
}

int main(int, char**)
{
    std::map<std::string, std::string> howdy;
    std::vector<std::pair<std::string, std::string>> there;
    assign(howdy, there.begin(), there.end());
}

Upvotes: 0

Views: 39

Answers (1)

Rakete1111
Rakete1111

Reputation: 48998

Just drop the type! :)

howdy = {there.begin(), there.end()};

This is called copy-list-initialization, you can read more about it here. It uses aggregate initialization if possible, or calls the appropriate non-explicit constructor to construct the object.

Upvotes: 1

Related Questions