小编4Le*_*Cat的帖子

当 return 语句、逗号运算符、花括号初始化列表和 std::unique_ptr 组合在一起时

在下面的代码中,为什么我会收到编译错误,而n = 8所有其他情况都正常?我的目的是报告一些错误并返回空指针,而不用不必要的大括号使代码混乱。我将使用 nullptr 来达到此目的,但我很好奇为什么{}无法使用逗号运算符进行编译,而它单独工作。

您可以在此处使用此代码。我使用C++20设置。

#include <cstdint>
#include <memory>

void oops(const char*) {
}

std::unique_ptr<uint8_t[]> please_do(int n) {
    if (n == 1)
        return std::unique_ptr<uint8_t[]>(); // compiles ok
    if (n == 2)
        return oops(""), std::unique_ptr<uint8_t[]>(); // compiles ok

    if (n == 3)
        return std::make_unique<uint8_t[]>(n); // compiles ok
    if (n == 4)
        return oops(""), std::make_unique<uint8_t[]>(n); // compiles ok

    if (n == 5)
        return nullptr; // compiles ok
    if (n == 6)
        return oops(""), nullptr; // compiles …
Run Code Online (Sandbox Code Playgroud)

c++

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

检查模板中任何类型的可调用函数指针是否为 nullptr

我创建了简单的包装器来捕获、报告和重新抛出异常(见下文)。它适用于函数、函数指针和std::function对象,但由于检查nullptr. 有没有办法尽可能简单地解决这个问题,以便包装器可以用于任何类型的可调用?谢谢!

#include <functional>

template<typename Func, typename TRet, typename... Args>
TRet wrapper(Func func, TRet exit_code_on_error, Args... args) {
    TRet exit_code = exit_code_on_error;
    //if (func) // this condition does not compile for lambdas and functors
    {
        try {
            exit_code = func(std::forward<Args>(args)...);
        } catch(...) {
            // report and possibly rethrow
            //throw;
        }
    }
    return exit_code;
}

int test1(double d) {
    return (int)d;
}

int test2(std::function<int (double)> f, double d) {
    return f(d);
}

struct TestFunctor { …
Run Code Online (Sandbox Code Playgroud)

c++ lambda templates

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

标签 统计

c++ ×2

lambda ×1

templates ×1