【发布时间】:2015-06-10 19:52:01
【问题描述】:
我希望在 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;
}
【问题讨论】:
-
std::is_base_of does not work well with my ... stuff。请参阅 Scott Meyer 的“Effective Modern C++”第 27 条。您需要std::is_base_of<Base, std::decay_t<T>>::value。 -
@kfsone
Base是一个类模板。 -
好吧,你明白我的意思。见ideone.com/d3Of8G
-
@kfsone 你不明白我的意思。
Base是一个类模板。不是一门课。 -
@Barry 在他的代码中,我没有引用他的代码。
std::is_base_of<TheBaseYouWantToTestAgainst, std::decay_t<T>>::value。开心吗?
标签: c++ templates std typetraits typename