为什么SFINAE不起作用?
Why SFINAE doesn't work?
我想检查类是否具有operator()。我尝试了以下sfinae。
#include <type_traits> //for std::true_type/false_type
#include <utility> //for std::declval
template <typename T, typename... A>
class has_call_operator {
private:
template <typename U, typename... P>
static auto check(U u, P... p) -> decltype(u(p...), std::true_type());
static auto check(...) -> decltype(std::false_type());
public:
using type
= decltype(check(std::declval<T>(), std::declval<A>()...));
static constexpr bool value = type::value;
};
一目了然,这正常工作。
#include <iostream>
struct test {
void operator()(const int x) {}
};
int main()
{
std::cout << std::boolalpha << has_call_operator<test, int>::value << std::endl; //true
return 0;
}
但是,抽象类未正确地工作。
#include <iostream>
struct test {
void operator()(const int x) {}
virtual void do_something() = 0;
};
int main()
{
std::cout << std::boolalpha << has_call_operator<test, int>::value << std::endl; //false
return 0;
}
为什么此代码不起作用?另外,您可以使此代码工作吗?
您按值乘以U
,因此也需要类型的构造。
通过const引用来解决该问题。
您可以看一下is_detected
,并且有类似的东西:
template <typename T, typename ...Ts>
using call_operator_type = decltype(std::declval<T>()(std::declval<Ts>()...));
template <typename T, typename ... Args>
using has_call_operator = is_detected<call_operator_type, T, Args...>;
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- SFINAE 示例不起作用
- 为什么void_t在SFINAE中不起作用,但enable_if起作用
- 为什么 SFINAE 在这个简单的成员函数重载中不起作用
- 为什么 SFINAE 在这个例子中不起作用?
- 为什么SFINAE在这种情况下不起作用?
- 为什么SFINAE不起作用?
- SFINAE:检测成员变量的存在在 g++ 上不起作用
- 为什么返回Sfinae转换操作员不起作用
- 构造函数上的SFINAE在VC2017中工作,但在clang / gcc中不起作用
- 请帮助我理解为什么SFINAE在这种情况下不起作用
- 为什么 SFINAE 在默认函数参数的右侧不起作用?
- 尽管使用了模板方法,但SFINAE不起作用