使用初始化列表创建单个项目向量 [英] Use initializer list to create single item vector

查看:77
本文介绍了使用初始化列表创建单个项目向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数func,该函数被重载以接受std::vector<Obj>自变量或Obj自变量.

I have a function func which is overloaded to take either a std::vector<Obj> argument or a Obj argument.

#include <vector>
#include <iostream>

class Obj {
    int a = 6;
};

void func(const std::vector<Obj>& a) {
    std::cout << "here" << std::endl;
}

void func(const Obj& a) {
    std::cout << "there" << std::endl;
}

int main() {
    Obj obj, obj2;
    func({obj});
    func({obj, obj2});
}

实际输出:

there
here

预期输出:

here
here

似乎{obj}不是初始化矢量,而是初始化一个对象.我猜要初始化的类型有一些优先顺序.如何精确控制它?

It seems {obj} doesn't initialize a vector, but rather an object. I guess there is some priority order when it comes to which type it initializes. How do I control it precisely?

(使用g ++(Ubuntu 8.3.0-6ubuntu1)8.3.0编译的示例.)

(Examples compiled with g++ (Ubuntu 8.3.0-6ubuntu1) 8.3.0.)

我发现了可能的重复项( c ++ 11 single函数调用中的元素向量初始化),尽管我的问题仍然没有答案:

I found a possible duplicate (c++11 single element vector initialization in a function call), although my question remains unanswered:

我知道{obj}可以解析为对象,而不是单个元素的向量,并且前者具有优先权.但是,是否可以使用{}创建单个项目向量(以便foo解析为std::vector重载)?我可以显式创建向量,但{}似乎更好.

I understand that {obj} can resolve to an object rather a vector of a single element and the former takes priority. But is there a way to use {} to create a single item vector (so that foo resolves to the std::vector overload)? I could create a vector explicitly but {} seems nicer.

推荐答案

如链接的问题副本(原文)中所述,没有办法强制采用超载的决议,而采用std::initializer_list.

As mentioned in the linked question duplicate (the original) there is no way to force the resolution in favour of the overload taking std::initializer_list.

原始签名(使用int简化):

The original signatures (using int to simplify):

void func(const std::vector<int> &a); 
void func(const int &a);

由于我已经遇到过很多次,所以我通常这样做:

Since I have encountered this many times I typically do this:

func(std::vector<int>{10});

我不知道执行此操作的任何更短方法,因为使用会执行相同操作的实际类型std::initializer_list更加冗长.但是从总体上讲,这至少使您所做的事情非常清楚,因为{10}如果不与类型一起使用的话,确实是模棱两可的.

I am not aware of any shorter way of doing this because using actual type std::initializer_list that would do the same is even more verbose. But on the birght side it at least makes what you are doing perfectly clear since {10} is really ambiguous if not accompanied with the type.

这篇关于使用初始化列表创建单个项目向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆