判断一个类型是否派生自CRTP基类

3
我想创建一个名为is_foo的函数,该函数可与enable_if结合使用,以确定类型是否派生自某个CRTP基类。下面的代码是我尝试实现is_foo函数的代码,但它实际上并不起作用。请问有人可以告诉我需要更改什么才能修复它吗?
谢谢。
#include <iostream>
#include <type_traits>
#include <functional>

using namespace std;

template <class Underlying, class Extra>
struct Foo
{
    int foo() const { return static_cast<const Underlying*>(this)->foo(); }
};

template<class T>
struct Bar : Foo<Bar<T>, T>
{
    int foo() const { return 42; }
};

template<class T>
struct is_foo { static const bool value = false; };

template<class Underlying, class Extra>
struct is_foo<Foo<Underlying, Extra> > { static const bool value = true; };

template<class T>
void test(const T &t)
{
    cout << boolalpha << is_foo<T>::value << endl;
}

int main()
{
    Bar<int> b;
    test(b);
}
2个回答

3

在Foo基类中添加一个typedef:

template < typename Derived >
struct crtp
{
  ...
  typedef int is_crtp;
};

实现一个has_field检查:

BOOST_MPL_HAS_XXX(is_crtp)

实现你的元函数:

template < typename T >
struct is_crtp_derived : has_is_crtp<T> {};

这是我想到的唯一正确捕获孙子类的方式。但它容易出现误判,所以你需要选择过于独特的命名以避免在其他地方被意外使用。另一种选择是通过is_base_of实现你的元函数。
template < typename T >
struct is_crtp_derived : std::is_base_of< crtp<T>, T> {};

当然,这不会捕捉到孙子辈。

0
你可以这样做:
typedef char (&yes)[1];
typedef char (&no )[2];


template<class container>
struct class_helper
{
    template<typename member> static no  has_implemented(member);
    template<typename member> static yes has_implemented(member container::*);  
};


template<class derived>
class base
{
protected:
    base() {}

public:
    void foo() 
    {
        static_assert(
            sizeof(class_helper<derived>::has_implemented(&derived::foo)) == sizeof(yes),
            "derived::foo not implemented"
        );
        static_cast<derived*>(this)->foo();
    }
};

但是你需要为每个定义的接口函数执行static_assert。可以使用enable_if使其更加通用:

static_cast<typename enable_if_c<
    sizeof(class_helper<derived>::has_member(&derived::foo)) == sizeof(yes), derived
>::type*>(this)->foo();

这种技术的缺点是,当“derived”中没有实现“foo”时,你必须处理令人困惑的编译器错误。

让我考虑一下。也许我很快就会有更好的解决方案;)

编辑: 好的,我更喜欢以下解决方案:

template<class derived>
class base
{
    template<std::size_t n> struct test {
        static_assert(n != sizeof(no), "derived doesn't implement used interface method");
    };

protected:
    base() {}

public:
    void bar()
    {        
        static_cast<derived*>(this)->bar();
        test<sizeof(class_helper<derived>::has_implemented(&derived::bar))>();
    }
};

请注意,在“protected”部分中定义基类的默认构造函数。如果不这样做,对成员函数的调用可能会引发访问冲突,因为它可能访问未分配的内存。声明类型为“base”的对象是不安全的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接