【发布时间】:2021-02-19 17:04:58
【问题描述】:
我将std::function 存储在可变参数类模板中(在类的构造函数中传递)。
这样做时,我想检查std::function 参数的类型是否与类模板的参数包中的类型相同。这是一个例子:
template<typename... T>
class Foo {
public:
explicit Foo(std::function<void(T...)> f)
: func(std::move(f)) {
// static_assert(...) How to formulate the static_assert here?
}
std::function<void(T...)> func;
};
int main()
{
Foo<int> fooA([](int& a){}); // does not compile
Foo<int&> fooB([](int a){}); // should not compile, but does
Foo<int&> fooC([](int& a){}); // should compile
}
如果类Foo<int&> 是用引用类型定义的,我想确保 lambda 也通过引用而不是值来获取int。
反过来(Foo<int> 和带有 int& 的 lambda)已经无法编译,因为 lambda 无法转换为按值采用 int 的函数。
使用static_assert(),我试图确保lambda 中的参数类型与Foo 中作为模板参数给出的类型相匹配。
到目前为止,我已经尝试解开函数参数:
template<typename... T>
struct ID {};
template<typename Func>
struct Unwrap;
template<typename R, typename... Args>
struct Unwrap<R(Args...)> {
using ArgsType = ID<Args...>;
};
template<typename R, typename... Args>
struct Unwrap<std::function<R(Args...)>>
: Unwrap<R(Args...)> {};
...
static_assert(std::is_same<typename Unwrap<std::function<void(T...)>>::ArgsType, ID<T...>>::value, "");
...
有没有办法实现我想要的? (对我来说考虑这样的检查是否有意义,或者使用我的class Foo 的人是否应该确保他提供了具有正确参数类型的 lambda?)
【问题讨论】:
标签: c++ variadic-templates std-function template-argument-deduction