问题描述
我在可变参数类模板中存储了一个 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?)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)