CRTP和Boost TTI

时间:2015-03-16 14:54:09

标签: c++ boost crtp

我使用gcc 4.9.0和clang 3.5.0测试了以下代码。该程序输出' true'正如所料。但是,如果我删除枚举前面的注释,则会变为“假”。这里发生了什么?如何确保has_mem布尔值设置为true。我的最终目标是在结构A中有一个成员函数,只有当类T具有某个成员函数时才通过enable_if启用它。

#include <iostream>
#include <boost/tti/has_member_function.hpp>

BOOST_TTI_HAS_MEMBER_FUNCTION(func)

template<class T>
struct A
{
  //enum : bool { has_mem= has_member_function_func<T,void,boost::mpl::vector<const T &> >::value };
  A()
  {
    std::cout << std::boolalpha
      << has_member_function_func<T,void,boost::mpl::vector<const T &> >::value
      << "\n";
  }
};

struct B : public A<B>
{
  void func( const B& ) {}
};

int main()
{
  B b;
}

1 个答案:

答案 0 :(得分:0)

我发现以下方法解决了我的问题。

#include <iostream>
struct empty_ {};

template<class derT>
struct A
{
  A( derT * ptr ) : m_ptr( ptr )  {}
  //
  template<class T=empty_>
  void  func()  { m_ptr->f(); }
private:
  derT  *m_ptr;
};

struct B : public A<B>
{
  B() : A<B>( this )  {}
  void  f()  { std::cout << "B::f\n"; }
};

struct C : public A<C>
{
  C() : A<C>( this )  {}
  void  g()  { std::cout << "C::g\n"; }
};

int main()
{
  B b;
  C c;
  b.func();
  c.g();
  // Does not compile (as disired) since class C does not have a function f()
  //c.func();
}

它有效,因为函数func是一个模板函数,因此SFINAE负责enable_if功能。

相关问题