【问题标题】:How do I create a dynamic list in template metaprogramming?如何在模板元编程中创建动态列表?
【发布时间】:2020-08-30 13:40:49
【问题描述】:

我一直在尝试模板元编程,但在制作动态列表时遇到了一些麻烦。我试过了

#include <iostream>
template<int I>
struct Int {

};
template<class _Value, class ..._Others>
struct List {
    typedef _Value Value;
    typedef List<_Others...> Next;
};
template<class _Value>
struct List<_Value, void> {
    typedef _Value Value;
    typedef void Next;
};

template<class _List>
void PrintList() {
    std::cout << typename _List::Value::I << "\n";
    PrintList<typename _List::Next>();
};
template<>
void PrintList<void>() {};

int main() {
    PrintList<List<Int<1>, Int<2>, Int<3>>>();
}

但是我得到了 2 个我无法弄清楚的编译错误。第一个是expected '(' before '&lt;&lt;' token 上的std::cout &lt;&lt; typename _List::Value::I &lt;&lt; "\n";。我不知道如何打印出 int 值(我也试过(typename _List::Value)::I)。

第二个错误是typedef List&lt;_Others...&gt; Next; 的模板参数数量错误。第一个参数不应该被限制为Value,其余的不是Others吗?

【问题讨论】:

  • 这里有两个独立的编译错误,根本原因完全不同,彼此无关,会有不同的答案。请为每个 stackoverflow.com 问题提出一个问题。你能把你的问题限制在一个问题上吗?

标签: c++ list templates variadic-templates


【解决方案1】:

您无法使用:: 语法访问模板参数。通常的约定是为类型添加typeusing,为值添加valueconstexpr static成员。

template<int I>
struct Int {
   constexpr static auto value=I;
};

然后使用 std::cout &lt;&lt; _List::Value::value &lt;&lt; "\n";。不是类型,所以把typename放在那里也是不正确的。

第二个错误是因为您定义了至少有一个参数的List,但您递归到最后为空的List&lt;_Others...&gt;。即使您想使用void 修复它,但您忘记将其添加到列表中,请尝试PrintList&lt;List&lt;Int&lt;1&gt;, Int&lt;2&gt;, Int&lt;3&gt;,void&gt;&gt;();

但是没有必要有一个哨兵值,看这个:

#include <iostream>
template<int I>
struct Int {
    static constexpr auto value=I;
};
//Define List as naturally having any number of arguments, even zero.
template<class...Ts>
struct List{};

//Non-empty specialization.
template<class Head, class...Tail>
struct List<Head,Tail...>{
    using head = Head;
    using tail = List<Tail...>;
};

template<class _List>
void PrintList() {
    std::cout <<  _List::head::value << "\n";
    PrintList<typename _List::tail>();
};
//Printing empty list.
template<>
void PrintList<List<>>() {};

int main() {
    PrintList<List<Int<1>, Int<2>, Int<3>>>();
}

在 C++ 中最好使用using,它们更具可读性并且可以模板化。

在 C++17 中,您可以使用折叠表达式:

template<typename...Elements>
void fold_print(List<Elements...>){
    ((std::cout<<Elements::value<<'\n'),...);
}
int main() {
    fold_print(List<Int<1>, Int<2>, Int<3>>{});
}

但是函数只能解包它们的参数,所以语法略有不同。或者,它还需要一个 struct 包装器来解压它们。

【讨论】:

    猜你喜欢
    • 2011-04-12
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    • 2012-06-09
    • 1970-01-01
    相关资源
    最近更新 更多