9

C++:对象判断是否含有某个成员函数

 3 years ago
source link: https://www.lpime.cn/article/116
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
C++:对象判断是否含有某个成员函数 - Ryan_naiquan

C++

sizeof在编译期执行,结果是函数返回类型的大小,函数并不会被调用。sizeof获取返回值的函数可以不定义。

#include <iostream>

template<typename T>
struct has_no_destroy {
	template<typename C>
	static char test(decltype(&C::no_destroy));


	template<typename C>
	static int32_t test(...);

	const static bool value = sizeof(test<T>(0)) == 1;
};
// 其作用就是用来判断是否有 no_destroy 函数

struct A {

};

struct B {
	void no_destroy() {}
};
struct C {
	int no_destroy;
};

struct D : B {

};

int main()
{
	printf("%d\n", has_no_destroy<A>::value);
	printf("%d\n", has_no_destroy<B>::value);
	printf("%d\n", has_no_destroy<C>::value);
	printf("%d\n", has_no_destroy<D>::value);
	system("PAUSE");
	return 0;
}

本文由 Ryan 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: 2021/05/18 15:54


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK