c++ - CRTP 和 boost TTI

标签 c++ boost crtp

我用 gcc 4.9.0 和 clang 3.5.0 测试了以下代码。该程序按预期输出“true”。但是,如果我删除枚举前面的注释,它就会变成“假”。这里发生了什么?如何确保 has_mem bool 值设置为 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;
}

最佳答案

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

#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 功能。

关于c++ - CRTP 和 boost TTI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29079920/

相关文章:

c++ - 迭代器模式示例在 C++ 中给出错误

c++ - 猜数字游戏

c++ - 获取当前命名空间和函数名(但不是完整签名)的宏?

Java 泛型——如何阅读这个 : Foo<T extends Bar<? extends Foo<T>>>?

c++ - 是否有一种技术可以让匿名结构的命名实例引用封闭类中的函数?

c++ - 'wsprintfW' : cannot convert parameter 1 from 'char [80]' to 'LPWSTR'

c++ - omp 单模拟通过 c++11

Boost程序选项检测是否使用默认值

c++ - 使用正则表达式替换匹配项

c++ - "Curiously Recurring Template Pattern"的实际用途