相关疑难解决方法(0)

为什么emplace_back()不使用统一初始化?

以下代码:

#include <vector>

struct S
{
    int x, y;
};

int main()
{
    std::vector<S> v;
    v.emplace_back(0, 0);
}
Run Code Online (Sandbox Code Playgroud)

使用GCC编译时出现以下错误:

In file included from c++/4.7.0/i686-pc-linux-gnu/bits/c++allocator.h:34:0,
                 from c++/4.7.0/bits/allocator.h:48,
                 from c++/4.7.0/vector:62,
                 from test.cpp:1:
c++/4.7.0/ext/new_allocator.h: In instantiation of 'void __gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = S; _Args = {int, int}; _Tp = S]':
c++/4.7.0/bits/alloc_traits.h:265:4:   required from 'static typename std::enable_if<std::allocator_traits<_Alloc>::__construct_helper<_Tp, _Args>::value, void>::type std::allocator_traits<_Alloc>::_S_construct(_Alloc&, _Tp*, _Args&& ...) [with _Tp = S; _Args = {int, int}; _Alloc = std::allocator<S>; typename std::enable_if<std::allocator_traits<_Alloc>::__construct_helper<_Tp, _Args>::value, void>::type = void]'
c++/4.7.0/bits/alloc_traits.h:402:4:   required …
Run Code Online (Sandbox Code Playgroud)

c++ vector uniform-initialization c++11

61
推荐指数
1
解决办法
6634
查看次数

安置POD

可能重复:
vector <struct>上的C++ 11\templace_back?

是否有可能与POD进驻?它似乎在Visual Studio 2012中不起作用:

struct X
{
    int a;
    int b;
};

void whatever()
{
    std::vector<X> xs;
    X x = {1, 2};

    // okay
    xs.push_back(x);

    // okay
    xs.emplace_back(x);

    //error C2661: 'X::X': error C2661: no overloaded function takes 2 arguments
    xs.emplace_back(1, 2);
}
Run Code Online (Sandbox Code Playgroud)

这只是Visual Studio 2012的一个缺点,还是放置POD根本无法在C++ 11中运行?

c++ vector pod c++11 emplace

11
推荐指数
1
解决办法
2565
查看次数

emplace和默认构造函数

鉴于以下代码,我很惊讶try_emplace无法使用在main函数的第一行中演示的默认构造函数,而是抱怨没有匹配的函数调用Element::Element(double, double).我是否误解了编译器创建默认构造函数的方式或使用try_emplace?我当然可以通过定义所有参数ctors来使这个代码工作Element,但这似乎是多余的.

#include <string>
#include <map>

struct Element
{    
    double a;
    double b;
};

int main(int argc, char** argv)
{
    Element e {2.0, 3.0};

    std::map<std::string, Element> my_map;
    my_map.try_emplace("hello", 2.0, 3.0);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ stl perfect-forwarding emplace

5
推荐指数
2
解决办法
288
查看次数

如何使用const值优雅地赋予可选项

我试图使用a std::optional来实例化一个对象(之前无效).我发现了一个烦人的情况,我不知道如何优雅地解决这个问题.

我有以下数据结构:

struct Foo {
    int foo1;
    float foo2;
};
Run Code Online (Sandbox Code Playgroud)

作为会员std::optional<Foo> foo_.

在一个功能

void Bar::bar(int const value1, float const value2) {
    foo_.emplace(value1, value2);
}
Run Code Online (Sandbox Code Playgroud)

令我惊讶的是,这无法编译(在GCC 7.1中),因为它试图调用Foowith 的构造函数int const&, float const&.现在天真的我试图专注emplace于:

foo_.emplace<int, float>(value1, value2);
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为它试图使用initializer_list那么.

所以我的问题是如何优雅地召唤出来?

c++ optional c++17

0
推荐指数
1
解决办法
843
查看次数