参数包感知标准::is_base_of()
Parameter pack aware std::is_base_of()
是否有可能有一个静态断言,即作为模板参数提供的类型是否实现了参数包中列出的所有类型,即。 一个参数包感知 std::is_base_of()?
template <typename Type, typename... Requirements>
class CommonBase
{
static_assert(is_base_of<Requirements..., Type>::value, "Invalid.");
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
parameter pack aware version of std::is_base_of()
public:
template <typename T> T* as()
{
static_assert(std::is_base_of<Requirements..., T>::value, "Invalid.");
return reinterpret_cast<T*>(this);
}
};
C++17 更新:对于 C++17 的折叠表达式,这几乎变得微不足道:
template <typename Type, typename... Requirements>
class CommonBase
{
static_assert((std::is_base_of_v<Type, Requirements> && ...), "Invalid.");
};
原文回答 (C++11/14):您可以使用包扩展和一些静态版本的std::all_of
:
template <bool... b> struct static_all_of;
//implementation: recurse, if the first argument is true
template <bool... tail>
struct static_all_of<true, tail...> : static_all_of<tail...> {};
//end recursion if first argument is false -
template <bool... tail>
struct static_all_of<false, tail...> : std::false_type {};
// - or if no more arguments
template <> struct static_all_of<> : std::true_type {};
template <typename Type, typename... Requirements>
class CommonBase
{
static_assert(static_all_of<std::is_base_of<Type, Requirements>::value...>::value, "Invalid.");
// pack expansion: ^^^
};
struct Base {};
struct Derived1 : Base {};
struct Derived2 : Base {};
struct NotDerived {};
int main()
{
CommonBase <Base, Derived1, Derived2> ok;
CommonBase <Base, Derived1, NotDerived, Derived2> error;
}
包扩展将扩展到你得到的值列表,方法是在std::is_base_of<Type, ?>::value
Requirements...
中插入每个类型作为问号,即对于main的第一行,它将扩展到static_all_of<true, true>
,对于第二行它将是static_all_of<true, false, true>
仅供将来参考,因为我刚刚遇到了这个问题,使用 C++17,您现在可以使用这样的折叠表达式:
template<typename Base, typename... Args>
constexpr auto all_base_of()
{
return (std::is_base_of<Base, Args>::value && ...);
}
static_assert(all_base_of<Base, A, B, C>());
相关文章:
- 如何反转整数参数包
- cmake如何在fedora工作站中找到boost静态库包
- 如何将enable-if与模板参数和参数包一起使用
- 在没有Xcode的情况下在Mac捆绑包中嵌入框架
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- 为什么这个音频包络不能通过开关的情况?
- 构造函数采用 Base&不被调用
- 模板元编程:如何将参数包组合成新的参数包
- 如何将C++闭包与变量参数同时重用——类似于JavaScript
- 将sharet_ptr<Derived>转换为shared_ptr<Base>
- AcquireCredentialsHandleA() 返回 PFX 文件的0x8009030e(安全包中没有可用的凭据
- 将 BASE 派生类存储在同一容器中
- C ++:在构造函数中使用参数包?
- struct.error:解压缩 C++ 结构时,解包需要 288 字节的缓冲区
- 避免矢量中的对象切片<Base><shared_ptr>
- MSYS2 MinGW程序包中缺少grpc_cpp_plugin协议
- 如何使我的 sizeof sum 结构与空参数包一起工作
- boost::asio UDP 广播客户端仅接收"fast"数据包
- 双模板参数包
- 参数包感知标准::is_base_of()