enable_if模板参数是 lambda(具有特定签名)
enable_if template param is lambda (with particular signature)
我有这个:
template<typename T>
class Image {
Image(int w, int h, T defaultVal){
for(int i=0; i<h; i++)
for(int j=0; j<w; j++)
pixel(j, i) = defaultVal;
}
template<typename F>
Image(int w, int h, F initializer){
for(int i=0; i<h; i++)
for(int j=0; j<w; j++)
pixel(j, i) = initializer(j, i);
}
// ...
};
我的目的是能够实例化这样的Image
:
Image<int> img0(w, h, 0); // image of zeroes
Image<int> imgF(w, h, [](int j, int i){ // checkerboard image
return (j/10+i/10) % 2;
});
但是,当然,第二个构造函数签名将与第一个构造函数签名冲突。为了解决此冲突,我想限制第二个构造函数的可能模板实例化。
我不想让它太复杂。你可以帮我吗?我的尝试:
template<typename F, typename = std::enable_if_t< // what now? how to check that F is callable (and if simple to check, with appropriate signature)
您正在寻找std::is_invocable
:
template<typename F, typename = std::enable_if_t<
std::is_invocable<F&, int, int>>
F&
因为您将其作为左值调用,然后它只是参数类型的列表。
以上需要C++17。它可以在 C++14 上实现,但在您的情况下,我们也可以采用更简单的方法,只需执行以下操作:
template <typename F, typename = decltype(std::declval<F&>()(1, 1))>
F&
的原因与上面相同,其余的表达式更熟悉。由于我们用int
调用,我们不关心INVOKE
允许的其他事情(例如指向成员的指针(。
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 可组合的lambda/std::函数与std::可选
- 我的简单if-else语句是如何无法访问的代码
- 如何将enable-if与模板参数和参数包一起使用
- 无论条件是否为true,if总是在c++中执行
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何建立使用模板函数的lambda函数的尾部返回类型
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 在通用 lambda 中使用 constexpr-if 来确定参数的类型
- 在 if 语句中返回布尔值的 lambda 表达式
- 'if constexpr branch'不会在模板函数内的 lambda 中被丢弃
- IF-ELSE语句的Lambda表达式的返回类型扣除
- if constexpr的False分支未在模板化lambda中丢弃
- c++ 11中的lambda函数定义中的if-else
- 是否有一种方法可以在IF中编写lambda表达式并捕获所有内容