gpt4 book ai didi

c++ - 将 std::function* 传递给模板参数

转载 作者:行者123 更新时间:2023-11-30 04:59:56 26 4
gpt4 key购买 nike

由于模板参数只能有指向对象的指针,并且不允许 lambda 文字,所以我一直在尝试找到一种方法来捕获 lambda 并将其作为 std::function 传递。由于参数不能是普通函数,我知道它必须是引用或指针。我已经尝试了 function& = * function_ptr 和 function* = &function_ptr,但都出现了关于转换的错误。尝试 & 和 & 导致 object has no linkage错误。是否可以传入 std::function 指针?

这是我目前的代码。

template<typename type>
std::function<bool(type)>* d = new std::function<bool(type)>([](type element) constexpr -> bool {return element;});

template<typename type = bool, std::function<bool(type)>& lambda = *d<type>>
struct Boolean {

const type element;

constexpr inline explicit Boolean(type element_in): element(element_in) {}

constexpr inline operator bool() {
return *lambda(element);
}
};

目标是在编译时通过模板参数有效地传递算法。我考虑过使用 if constexpr 和 nullptr default 来为 lambda 提供我实际想要的默认值,但我不明白为什么有必要这样做。

明确地说,我试过:

*lambda = d<type> , *lambda = &d<type> , &lambda = &d<type> , 和 &lambda = *d<type> .可能还有其他人在我的争夺中,但我清楚地记得这些。

对于错误,我收到了:

* Concepts::Operators::d<bool>’ is not a valid template argument for type ‘std::function<bool(bool)>&’ because it is not an object with linkage ,

还有许多关于指针和引用之间的错误转换。

我希望有人能解释为什么尝试将指针与引用匹配似乎不起作用,因为我自己也不确定。

很早以前,我也尝试过将 d 作为对象本身 ( std::function<bool(type)> d = [](type element) constexpr -> bool {return element}; ),但我也没有成功。`

最佳答案

如果你想让你的 constexpr inline operator bool() 实际上是 constexpr,你不能使用 std::function,因为它没有 constexpr 构造函数。

但是,由于您使用的是 constexpr lambdas (C++17),因此您还应该能够在 template parameters 中使用 auto 类型.它可用于将 lambda 传递给您的模板:

template<typename type>
auto d = [](type element) constexpr -> bool {
return element;
};

template<typename type = bool, auto& lambda = d<type>>
struct Boolean {
const type element;

constexpr inline explicit Boolean(type element_in): element(element_in) {}

constexpr inline operator bool() {
return lambda(element);
}
};

Live demo

关于c++ - 将 std::function* 传递给模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51005696/

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