小编Mic*_*rek的帖子

有条件地指定 noexcept 函数

假设我声明了这样的函数noexcept

int pow(int base, int exp) noexcept
{
    return (exp == 0 ? 1 : base * pow(base, exp - 1));
}
Run Code Online (Sandbox Code Playgroud)

从我对 C++ 的了解很少,但慢慢增长的知识来看,noexcept当我确定该函数不会抛出异常时,我可以做到这一点。我还了解到它可以在某个值范围内,假设我在小于 10 和小于 8noexcept时考虑我的函数(仅作为示例)。我如何声明这个函数处于这样的值范围内?或者我最多能做的就是给其他程序员留下评论,说它应该在某个特定的范围内?expbasenoexcept

c++ noexcept

4
推荐指数
1
解决办法
261
查看次数

重载 std::array << 运算符

我在尝试为 std::array 重载运算符 << 时遇到问题。对于所有其他集合,我尝试以随意的方式进行:

std::ostream& operator<<(std::ostream& os, std::array<int> const& v1)
{
    for_each(begin(v1), end(v1), [&os](int val) {os << val << " "; });
    return os;
}
Run Code Online (Sandbox Code Playgroud)

但是编译器希望我添加有关数组大小的信息,这不会使它成为任何整数数组的通用解决方案。我知道如果我想为一般类型制作它,我将不得不使用模板,但现在我只想为整数数组制作它。

c++ c++11 c++14

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

将派生类对象添加到基类的向量&lt;unique_ptr&gt;

因此,在我的代码中,我尝试将unique_ptr对象添加到从derived类到vector基类的对象。我收到此错误:

E0304 没有重载函数的实例“std::vector<_Ty, _Alloc>::push_back [with _Ty=std::unique_ptr<Organism, std::default_delete<Organism>>, _Alloc=std::allocator<std::unique_ptr <Organism, std::default_delete<Organism>>>]" 与参数列表匹配

基类的代码(如果您需要更多,请告诉我,尽量少写代码):

vector<unique_ptr<Organism>>  World::generate_organisms(int act_level)
{
    vector<unique_ptr<Organism>> organism_list = get_vector();
    coordinates sheep_pos(10, 2);
    //getting error in next line
    organism_list.push_back(make_unique<Sheep>(sheep_pos, *this));

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

派生类的代码:

.h文件

class Sheep : Organism
{
    Sheep( coordinates organism_pos, World* world);
};
Run Code Online (Sandbox Code Playgroud)

.cpp文件

Sheep::Sheep( coordinates organism_pos, World* act_world)
    :
    Organism(organism_pos, act_world)
{
    this->armor = 0;
    this->damage = 2;
    this->health = 10;
    this->vigor = 10;
}
Run Code Online (Sandbox Code Playgroud)

c++ inheritance derived-class unique-ptr c++11

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

标签 统计

c++ ×3

c++11 ×2

c++14 ×1

derived-class ×1

inheritance ×1

noexcept ×1

unique-ptr ×1