相关疑难解决方法(0)

如何检测类中是否有特定的成员变量?

为了创建算法模板函数,我需要知道类中的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)

c++ templates g++ sfinae visual-studio

62
推荐指数
5
解决办法
3万
查看次数

如何检查一个类是否具有一个或多个具有给定名称的方法?

有许多不同的技巧可用于检查类是否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)

c++ methods templates sfinae c++14

2
推荐指数
1
解决办法
121
查看次数

标签 统计

c++ ×2

sfinae ×2

templates ×2

c++14 ×1

g++ ×1

methods ×1

visual-studio ×1