【问题标题】:C++ Iterate over template variable instantiationsC++ 迭代模板变量实例化
【发布时间】:2021-11-11 16:24:31
【问题描述】:

看看这个:

#include <vector>
#include <iostream>

template<class T>
std::vector<T> vec{};

int main() {
    vec<short>.push_back(5);
    vec<int>.push_back(10);
    vec<long int>.push_back(15);
}

vec 变量是模板化的,但不知道发生了哪些可能的实例化。在这种情况下,很明显:shortintlong。但是更复杂的情况呢?如何跟踪模板实例化?

我的目标是能够遍历所有vec 实例。类似的东西

for (std::any element : vec) {
    delete element; // Or any common logic the types might have (can guarantee with concepts)
}

【问题讨论】:

  • "vec 变量是模板化的" 不,您有一个实例化变量s 的模板。 vec 不是变量。 vec&lt;int&gt; 是与 vec&lt;short&gt; 不同的变量。
  • @Caleth 请编辑问题
  • 删除不是整数通用的操作。
  • 没有所有类型通用的操作
  • @eerorika 对于vec 可能持有的内容没有任何限制。这是伪代码。

标签: c++ templates


【解决方案1】:

如果您将vec 包装在一个函数中,并且有一个类型擦除的“对vec&lt;T&gt; 执行操作”接口,您也许可以做一些事情。

您需要预先指定要对各种vec&lt;T&gt;()s 执行的所有操作。

template <typename T>
concept printable = requires (T t) { std::cout << t; }

template <printable T>
std::vector<T> & vec();

struct vec_printer
{
    vec_printer(std::type_index index) : index(index) {}

    virtual ~vec_printer() = default;
    virtual void print() = 0;
    // etc...

    std::type_index index;
};

struct vec_printer_compare 
{
    using ptr = std::unique_ptr<vec_printer>;
    bool operator(const ptr & lhs, const ptr & rhs){ return lhs->index < rhs->index; }
};

std::set<std::unique_ptr<vec_printer>, vec_printer_compare> vec_printers;

template <printable T>
struct vec_printer_impl
{
    vec_printer_impl() : vec_printer(typeid(T)) {}
    void thing_one() { for (auto & v : vec<T>()) { std::cout << v; } }
};

template <printable T>
std::vector<T> & vec()
{
    vec_printers.emplace(std::make_unique<vec_printer_impl<T>>());
    static std::vector<T> v;
    return v;
}

void print_vecs()
{
    for (auto & printer : vec_printers) { printer->print(); }
}

【讨论】:

  • 啊,大 ol 静态函数变量技巧。完全颠覆了我的认知
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多