C++ 模板元编程 : Inheritance from template template parameter

标签 c++ templates template-meta-programming policy policy-based-design

#include <type_traits>

template <typename T1, typename T2, typename is_allocated>
struct mutable_storage {};

template <
    template<typename, typename, typename> class storage_t,
    typename T2           = void,
    typename is_allocated = std::false_type
>
class Buffer : storage_t<Buffer<storage_t,void,void>, T2, is_allocated>
{};



int main() {
    typedef Buffer<mutable_storage> example_buffer;
}

此代码编译(至少使用遵循 C++14 的 GNU GCC 编译器)。但是,我不喜欢使用的语法

class Buffer : storage_t<Buffer<storage_t,void,void>, T2, is_allocated>

因为它不应该要求 Buffer 是专门的:我希望 Buffer 被识别为模板模板参数,例如:

class Buffer : storage_t<Buffer, T2, is_allocated>

然后我希望 mutable_storage 结构能够识别像这样的模板特化

template <typename T2, typename is_allocated>
struct mutable_storage<Buffer, T2, is_allocated> { ... };

(当然不允许,因为“Buffer”不是一种类型,所以也应该改变)。 但是它现在使用的方式,能够专注于类型 缓冲区感觉有点讨厌。例如,使用 typedef

 typedef Buffer<storage_t, void, void> Buffer_Policy

也觉得有点恶心。我正在寻找一种更清洁的方法。我试图制作一个模板模板模板参数,但这会导致模板参数内的额外模板无限流动(我不确切知道模板 <...> 是如何工作的,所以也许是这样?),因为Buffer 继承自需要另一个 Buffer 才能声明 storage_t 的东西。我也尝试过使用隐式类,即 inner_storage_t。这也没有导致成功。有没有人有建议以使程序更清洁?顺便说一下,如果您发现任何其他错误或效率低下的地方,请随时提出来。感谢阅读并可能提供帮助。

最佳答案

由于 T1 仅用于模板特化选择,您实际上不必使用 Buffer 本身。您可以改用标签类型。

将其隐藏在命名空间中还可以避免标签污染封闭命名空间的其余部分。

#include <type_traits>

template <typename T1, typename T2, typename is_allocated>
struct mutable_storage {};

namespace storage_tags {
  struct Buffer_T {};
}

template <
    template<typename, typename, typename> class storage_t,
    typename T2           = void,
    typename is_allocated = std::false_type
>
class Buffer : public storage_t<storage_tags::Buffer_T, T2, is_allocated> { 

};

关于C++ 模板元编程 : Inheritance from template template parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50646362/

相关文章:

c++ - IBM MQ 升级导致错误 2059 和错误 2018

c++ - C++中的哈希表/无序映射

c++ - 为什么 gcc 提示 "error: type ' intT' of template argument '0' depends on a template parameter”?

c++ - C++ 中的 Word 插件,IDTEXtensibility2,如何编写事件处理程序? (也需要通用 COM 帮助)

c++ - 在 C++ 中,对象和指向对象的指针有什么区别?

c++ - 为什么模板只能在头文件中实现?

c++ - 如何扩展 std::apply 以处理非元组类型?

c++ - 模版的歧义

c++ - 多类型STL映射

c++ - 确定 (c++) 迭代器是否反向