Yip*_*Yay 4 c++ templates type-traits
我想知道在C++中是否有可能以某种方式处理以下情况:
情况1) (易于处理)
class BasicFacility { }
template <typename U1, typename U2> class Facility : public BasicFacility { }
Run Code Online (Sandbox Code Playgroud)
现在假设我们想要一些编译时断言,我们想检查任意类型是否typename T建模Facility.这很简单:
(boost::is_base_of<BasicFacility, T>::type)
Run Code Online (Sandbox Code Playgroud)
情况2) (???)
现在让我们假设在相同的情况下我们只有模板类:
template <typename U1, typename U2> class Facility { }
Run Code Online (Sandbox Code Playgroud)
显然我们不能从情境一中使用相同的解决方案,因为我们不能写statement<Facility, T>(Facility模板本身).
那么,有没有一种方法(可能是脏的,涉及丑陋的强制转换,特定于对齐,可能有任何作用)来检查某些T实际上是否等于某些template type而没有引入特定的空(辅助)基类(因为有时你根本不能)?
谢谢.
滚动自己的测试非常简单:
template <typename T>
struct is_facility : public boost::false_type { };
template <typename U1, typename U2>
struct is_facility< Facility<U1, U2> > : public boost::true_type { };
Run Code Online (Sandbox Code Playgroud)
IIUC,您想确保某个模板参数是Facility模板的实例。这很简单:
template< typename Policy >
struct some_template; // note: only declared
template< typename U1, typename U1 >
struct some_template< Facility<U1,U2> > {
// implementation
};
Run Code Online (Sandbox Code Playgroud)
当然,您也可以概括/形式化:
template< typename T >
struct AssertFacility {}; // note: empty
template< typename U1, typename U2 >
struct AssertFacility< Facility<U1,U2> > {
typedef Facility<U1,U2> result_t;
};
template< typename Policy >
class some_class {
typedef AssertFacility<Policy>::result_t just_an_assertion;
public:
// more stuff
};
Run Code Online (Sandbox Code Playgroud)