在模板参数中查找typename的typename

时间:2015-06-10 19:52:02

标签: c++ templates std typetraits typename

当foo从base获取任何内容时,我希望编译以下代码,否则会出现编译错误。我编写了类型特征类is_Base,因为std::is_base_of与我的模板内容不兼容。我很亲密我使用static_passoff的东西让它工作,但我不想使用它。那么如何在没有static_passoff hack的情况下编写enable_if?以下是正在运行的版本:http://coliru.stacked-crooked.com/a/6de5171b6d3e12ff

#include <iostream>
#include <memory>

using namespace std;

template < typename D >
class Base
{
public:
    typedef D EType;
};

template<class T>
struct is_Base
{
    using base_type = typename std::remove_cv<typename std::remove_reference<T>::type>::type;

    template<class U>
    static constexpr std::true_type test(Base<U> *) { return std::true_type(); }
    static constexpr std::false_type test(...) { return std::false_type(); }

    using value = decltype( test((T*)0) );
};

template < typename A >
using static_passoff = std::integral_constant< bool, A::value >;

template <typename T, typename = typename std::enable_if< static_passoff< typename is_Base< T >::value >::value >::type >
void foo(T const&)
{
}


class Derived : public Base<Derived> {};
class NotDerived {};


int main()
{
    Derived d;
    //NotDerived nd;

    foo(d);
    //foo(nd); // <-- Should cause compile error

    return 0;
}

2 个答案:

答案 0 :(得分:2)

鉴于您的代码确实有效,我并不完全确定我理解您的问题。但从风格上来说,对于产生类型的元函数,该类型应该命名为type。所以你应该:

using type = decltype( test((T*)0) );
      ^^^^

或者,为了避免零指针演员黑客攻击:

using type = decltype(test(std::declval<T*>()));

此外,您的test不需要定义。只是声明。我们实际上并没有调用它,只是检查它的返回类型。它也不必是constexpr,所以这就足够了:

template<class U>
static std::true_type test(Base<U> *);
static std::false_type test(...);

一旦你拥有了它,你可以使用别名:

template <typename T>
using is_Base_t = typename is_Base<T>::type;

并使用别名:

template <typename T, 
          typename = std::enable_if_t< is_Base_t<T>::value>>
void foo(T const&)
{
}

答案 1 :(得分:0)

在评论中盲目绊倒后,我发现我可以使用is_Base<T>::type::value而不使用任何typename个关键字。在尝试删除之前的static_passoff时,我一直放入typename。我一直和那个人混在一起。无论如何,这是最后的代码,其中有一些来自巴里答案的柚木:

#include <iostream>
#include <memory>

using namespace std;

template < typename D >
class Base
{
public:
    typedef D EType;
};

template<class T>
struct is_Base
{
    using base_type = typename std::remove_cv<typename std::remove_reference<T>::type>::type;

    template<class U>
    static constexpr std::true_type test(Base<U> *) { return std::true_type(); }
    static constexpr std::false_type test(...) { return std::false_type(); }

    using type = decltype(test(std::declval<T*>()));
};

template <typename T, typename = typename std::enable_if< is_Base< T >::type::value >::type >
void foo(T const&)
{
}


class Derived : public Base<Derived> {};
class NotDerived {};


int main()
{
    Derived d;
    //NotDerived nd;

    foo(d);
    //foo(nd); // <-- Should cause compile error

    return 0;
}
相关问题