gpt4 book ai didi

c++ - [[nodiscard]] 在 std::function 返回类型定义中?

转载 作者:行者123 更新时间:2023-12-03 06:49:44 35 4
gpt4 key购买 nike

我想知道是否有办法拥有这样的东西:

using CallbackType = std::function<[[nodiscard]]bool(void)>; 
(我知道上面的代码不会被编译并提示 nodiscard 不能应用于类型!)
我的目标是强制回调的调用者检查它的返回值!

最佳答案

你可以做这样的事情

#include <iostream>
#include <utility>

template <typename R, typename... Args>
struct Function {
using Fn = R (*)(Args...);

Fn fn;

explicit Function(Fn fn) : fn{fn} {}

[[nodiscard]] R operator()(Args... args) {
return (*fn)(std::forward<Args>(args)...);
}
};

template <typename R, typename... Args>
Function(R (*)(Args...)) -> Function<R, Args...>;


bool bar(const int& x) { return x % 2 == 0; }

int main() {
Function{&bar}(10);
}
警告:
Compiler stderr

<source>: In function 'int main()':

<source>:24:17: warning: ignoring return value of 'R Function<R, Args>::operator()(Args ...) [with R = bool; Args = {const int&}]', declared with attribute 'nodiscard' [-Wunused-result]

24 | Function{&bar}(10);

| ~~~~~~~~~~~~~~^~~~

<source>:12:19: note: declared here

12 | [[nodiscard]] R operator()(Args... args) {

| ^~~~~~~~
编辑:
扩展到成员函数 (+const) + lambda(带推导指南)
template <typename T, typename = std::void_t<>>
struct Function;

template <typename R, typename... Args>
struct Function<R (*)(Args...)> {
using Fn = R (*)(Args...);

Fn fn;

explicit Function(Fn fn) : fn{fn} {}

[[nodiscard]] R operator()(Args... args) {
return fn(std::forward<Args>(args)...);
}
};

template <typename T, typename R, typename... Args>
struct Function<R (T::*)(Args...)> {
using MFn = R (T::*)(Args...);

T* t;
MFn mfn;

Function(T* t, MFn mfn) : t{t}, mfn{mfn} {}

[[nodiscard]] R operator()(Args... args) {
return (t->*mfn)(std::forward<Args>(args)...);
}
};

template <typename T, typename R, typename... Args>
struct Function<R (T::*)(Args...) const> {
using MFn = R (T::*)(Args...) const;

const T* t;
MFn mfn;

Function(const T* t, MFn mfn) : t{t}, mfn{mfn} {}

[[nodiscard]] R operator()(Args... args) {
return (t->*mfn)(std::forward<Args>(args)...);
}
};

template <typename T>
struct Function<T, std::void_t<decltype(&T::operator())>> final
: Function<decltype(&T::operator())> {
explicit Function(const T& t)
: Function<decltype(&T::operator())>(&t, &T::operator()) {}
};

template<typename T>
Function(T) -> Function<T>;

template<typename T, typename R, typename ...Args>
Function(T*, R(T::*)(Args...)) -> Function<R(T::*)(Args...)>;

template<typename T, typename R, typename ...Args>
Function(const T*, R(T::*)(Args...) const) -> Function<R(T::*)(Args...) const>;

void foo() {}

struct Foo
{
void foo() const {}
};

int main() {
Function{&foo}();
Function{[]{}}();
Foo foo{};
Function{&foo, &Foo::foo}();
}

关于c++ - [[nodiscard]] 在 std::function 返回类型定义中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63954142/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com