为了创建算法模板函数,我需要知道类中的x或X(和y或Y)是模板参数.当我的函数用于MFC CPoint类或GDI + PointF类或其他类时,它可能很有用.他们都使用不同的x.我的解决方案可以简化为以下代码:
template<int> struct TT {typedef int type;};
template<class P> bool Check_x(P p, typename TT<sizeof(&P::x)>::type b = 0) { return true; }
template<class P> bool Check_x(P p, typename TT<sizeof(&P::X)>::type b = 0) { return false; }
struct P1 {int x; };
struct P2 {float X; };
// it also could be struct P3 {unknown_type X; };
int main()
{
P1 p1 = {1};
P2 p2 = {1};
Check_x(p1); // must return true
Check_x(p2); // must return false
return …Run Code Online (Sandbox Code Playgroud) 有许多不同的技巧可用于检查类是否Foo具有名为 的方法bar。例如:
std::void_t<decltype(static_cast<ing(Foo::*)(char) const>(&Foo::bar))>std::void_t<decltype(&Foo::bar)>如果Foo有多个名为 的方法bar,则前者继续正常工作(因为最多一个重载将与 兼容static_cast),但是,后者将中断,大概是因为decltype(&Foo::bar)变得不明确。
是否有一种技术可以检测一个类是否具有一个或多个具有给定名称的方法,而不管方法签名如何?如果它可以在 C++14 中工作,那就加分了。
示例代码(Godbolt 链接):
#include <type_traits>
template<typename T, typename = void> struct HasIntBar_t : std::false_type {};
template<typename T> struct HasIntBar_t<T, std::void_t<decltype(static_cast<int(T::*)(char)>(&T::bar))>> : std::true_type {};
template<typename T> inline constexpr bool HasIntBar = HasIntBar_t<T>::value;
template<typename T, typename = void> struct HasAnyBar_t : std::false_type {};
template<typename T> struct HasAnyBar_t<T, std::void_t<decltype(&T::bar)>> : std::true_type {};
template<typename T> inline constexpr bool …Run Code Online (Sandbox Code Playgroud)