gpt4 book ai didi

c++ - 模板参数依赖 [[nodiscard]]

转载 作者:可可西里 更新时间:2023-11-01 18:39:49 25 4
gpt4 key购买 nike

我有一个函数对象,它是另一个函数的包装器:

template <typename FuncT>
class Wrapper
{
private:
FuncT funcToWrap;

public:
Wrapper(FuncT ftw) : funcToWrap(ftw){};

template<typename ...ARG>
typename std::result_of<FuncT(ARG&&...)>::type operator()(ARG&&... args){
return funcToWrap(std::forward<ARG>(args)...);
}
};

int main(){
std::function<void()> testfunc = [](){ std::cout << "Test" << std::endl; };
Wrapper<decltype(testfunc)> test{testfunc};
test();
}

我想做的是标记operator()作为[[nodiscard]]如果std::result_of<FuncT(ARG&&...)>::type不是 void .

我注意到当我把 [[nodiscard]]如果返回类型的模板评估为 void ,它只会被我的编译器忽略。

这是我可以依赖的行为吗?它是否以任何方式标准化?

最佳答案

您可以使用 SFINAE 在两个重载的 operator () 之间进行选择:其中一个返回 void,另一个用于其余用 [[nodiscard]] 属性:

#include <type_traits>
#include <iostream>

template <typename FuncT>
class Wrapper
{
private:
FuncT funcToWrap;

public:
Wrapper(FuncT ftw) : funcToWrap(ftw) {}

template <typename ...ARG, typename T = std::invoke_result_t<FuncT, ARG...>>
std::enable_if_t<std::is_void_v<T>> operator()(ARG&&... args) {
std::cout << "Test 1" << std::endl;
return funcToWrap(std::forward<ARG>(args)...);
}

template <typename ...ARG, typename T = std::invoke_result_t<FuncT, ARG...>>
[[nodiscard]] std::enable_if_t<!std::is_void_v<T>, T> operator()(ARG&&... args) {
std::cout << "Test 2" << std::endl;
return funcToWrap(std::forward<ARG>(args)...);
}
};

int main() {
auto testfunc1 = [] { };
Wrapper test1{testfunc1};
test1(); // <-- No warnings should be issued here

auto testfunc2 = [] { return 0; };
Wrapper test2{testfunc2};
test2(); // <-- Warning issued here
}

关于c++ - 模板参数依赖 [[nodiscard]],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56557786/

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