可调用的类成员检测器习语和C++11最终版本
Callable class member detector idiom and C++11 final
我想检测一个类型是否是可调用的,以下内容适用于所有未标记为final
:的类
template<typename T>
struct is_callable_impl {
private:
typedef char(&yes)[1];
typedef char(&no)[2];
struct fallback {
void operator()();
};
struct derived
: T, fallback {};
template<typename U, U> struct check;
template<typename>
static yes test(...);
template<typename C>
static no test(check<void (fallback::*)(), &C::operator()>*);
public:
static constexpr bool value = sizeof(test<derived>(0)) == sizeof(yes);
};
template<typename T>
struct is_callable
: std::conditional<
std::is_function<T>::value,
std::true_type,
typename std::conditional<
std::is_class<T>::value,
is_callable_impl<T>,
std::false_type
>::type
>::type {};
这是C++03方式的成员检测器习惯用法,但我们现在可以将SFINAE表达式与decltype
一起使用。我不知道如何在类型上检测任何过载的operator()
?以上使用fallback
来检测T.上是否没有可用的可调用函数指针
实时演示
我会做
#define DEFINE_HAS_SIGNATURE(traitsName, funcName, signature)
template <typename U>
class traitsName
{
private:
template<typename T, T> struct helper;
template<typename T>
static std::uint8_t check(helper<signature, &funcName>*);
template<typename T> static std::uint16_t check(...);
public:
static
constexpr bool value = sizeof(check<U>(0)) == sizeof(std::uint8_t);
}
DEFINE_HAS_SIGNATURE(is_callable, T::operator (), void (T::*)() const);
演示
相关文章:
- 在 C++11 及更高版本中,有没有办法初始化初始值设定项列表中的向量?
- 在Visual Studio中单实例Qt应用程序版本5.11.1中,在所有其他窗口的顶部打开Qt MainWindow
- 我将 Makefile 更改为 C++11 版本,但仍然收到列表初始值设定项错误
- C++11 谷物序列化 - 版本控制
- 如何获得CMake Tools以在Visual Studio Code中编译具有C++11(或更高版本)功能的程序?
- C++模板元编程(版本小于 17,最好是 11)
- C++11 功能 std::map::at 编译旧版本的C++
- 有没有办法在旧版本的 c++ 中实现初始值设定项列表(有点)(在 c++11 之前)
- 在C 11或更高版本中,是否可以通过Lambda来实现单方法纯Virtual C 接口
- ld.so.1:protoc:fatal:libstdc++.so.6:在 Solaris 11 中找不到版本"GLIBCXX_3.4.20"
- C++11及更高版本:shared_ptr,用于管理由低级C库提供的系统资源
- 如何在 CMake 目标上请求 C++11 或更高版本
- C++11 具有与不同版本的 GCC 兼容的功能
- 使用C 11 /最近的G 版本(4.7 / 4.6)的可移植性
- Solaris 上的 GNU gcc/g++ 编译器版本,支持 C++11/14
- 用于循环的c++(c++11方式和旧版本方式)
- C++旧版本(不是 C++11)-- map -> 覆盖哈希代码
- 为什么不能在C++11或更高版本的函数声明中定义结构
- 获取 Howard Hinnant 的 short_alloc(C++11 版本)在 Visual C++ 2015 中编译
- 正在检查成员是否存在,可能在基类C++11版本中