大佬教程收集整理的这篇文章主要介绍了c – 使用std :: is_same进行元编程,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
template <class T> class A { public: #if std::is_same<T,int> void has_int() {} #elif std::is_same<T,char> void has_char() {} #endif }; A<int> a; a.has_int(); A<char> b; b.has_char();
std::enable_if
条件启用它们:
#include <type_Traits> template <class T> class A { public: template<typename U = T> typename std::enable_if<std::is_same<U,int>::value>::type has_int() {} template<typename U = T> typename std::enable_if<std::is_same<U,char>::value>::type has_char() {} }; int main() { A<int> a; a.has_int(); // OK // a.has_char(); // error }
如果类很大并且有许多函数需要与T无关,那么the other answer的解决方案可能不可行.但是你可以通过继承另一个仅用于这些特殊方法的类来解决这个问题.然后,您只能专门化该基类.
在C 14中,有方便的类型别名,因此语法可以变为:
std::enable_if_t<std::is_same<U,int>::value>
而C 17甚至更短:
std::enable_if_t<std::is_same_v<U,int>>
以上是大佬教程为你收集整理的c – 使用std :: is_same进行元编程全部内容,希望文章能够帮你解决c – 使用std :: is_same进行元编程所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。