相关疑难解决方法(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万
查看次数

如何使用布尔模板参数启用成员函数?

我希望一个类具有 , 的两种不同实现push,并根据布尔模板参数进行选择。我尝试使用本答案中描述的 SFINAE 原则,如下所示:

template<class T, bool foo=true>
class Bar {
  template <>
  typename std::enable_if<foo>::type
  push(const T& value) { /* one implementation */}

  template <>
  typename std::enable_if<!foo>::type
  push(const T& value) { /* another implementation */ } 
}
Run Code Online (Sandbox Code Playgroud)

但是,我push在 gcc 下收到“无法专门化类范围内的函数”的错误,我不明白为什么。尽管我的代码与链接答案中的代码不完全一样,但它似乎非常相似,我无法发现关键区别。

我还尝试使用与此答案中建议的语法类似的语法,但它也不起作用(错误是“不能重新声明类成员”):

  template <bool enable=foo>
  typename std::enable_if<enable>::type
  push(const T& value) { /* one implementation */}

  template <bool enable=!foo>
  typename std::enable_if<enable>::type
  push(const T& value) { /* another implementation */ } 
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

c++ templates sfinae

4
推荐指数
1
解决办法
1324
查看次数

标签 统计

c++ ×2

sfinae ×2

templates ×2

g++ ×1

visual-studio ×1