【问题标题】:How to partially fill in a C++ Template Template Parameter without creating a new class如何在不创建新类的情况下部分填写 C++ 模板模板参数
【发布时间】:2020-12-14 11:32:01
【问题描述】:

是否有可能以某种方式“部分”填充模板模板参数的参数,而不为每个大小引入新类或 using 语句?

我的代码:

#include <vector>
#include <array>
#include <tuple>

struct A { int a = 1; };
struct B { int b = 1; };
struct C { int c = 1; };

template<template<class...> class _Storage, typename... _Components>
struct Foo {
    using Storage = std::tuple<_Storage<_Components>...>;
    Storage storage;

    /* ... do stuff with storage ... */
};

int main() {
    Foo<std::vector,A,B,C> fooV;            // works
    Foo<std::array<...,16>,A,B,C> fooA;     // doesn't work
    return 0;
}

显然,上面的“fooA”行是无效的 C++,但它表明了我的意图。

  • fooV 将创建我的 Foo 类,其中 3 个组件存储在 std::vectors 中,所以 std::vector&lt;A&gt; 用于 A,std::vector&lt;B&gt; 用于 B,等等。
  • fooA 将创建我的 Foo 类,其中 3 个组件存储在最大大小为 16 的 std::array 中,因此 std::array&lt;A, 16&gt; 用于 A,std::array&lt;B, 16&gt; 用于 B,等等。

实现我的意图的唯一方法是引入模板化 using 语句:

template<typename _T> using MyArray16 = std::array<_T, 16>;

不是很好用:

Foo<MyArray16,A,B,C> fooA;      // works

但是,我必须为我需要的每个数组大小引入新的using 类型,这远非最佳。当然,我可以使用#define 轻松做到这一点,并且所有这些都可以避免代码重复,但它仍然远非最佳。

有没有人知道在不引入新类或using 语句的情况下实现此目的的语法方法?

【问题讨论】:

  • 不是您问题的答案,但您不应使用以下划线后跟大写字母开头的名称,因为这些名称由编译器保留。不久前还有另一个问题,这实际上导致某些编译器的编译错误
  • 真的吗?我在 2005 年一直在做这个,从来没有遇到过任何问题,但很高兴知道谢谢!

标签: c++ arrays templates


【解决方案1】:

老橡皮鸭又来了。突然间我找到了答案。它仍然需要一个额外的类,但我不需要每个尺寸的新类!

template<size_t N> struct MyArray {
    template<typename _T>
    using Type = std::array<_T, N>;
};

Foo<MyArray<16>::Type,A,B,C> fooA16;        // works!
Foo<MyArray<256>::Type,A,B,C> fooA256;      // works!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2021-08-30
    • 2012-10-11
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2018-02-28
    相关资源
    最近更新 更多