Compile-Time Topological Sort Exceeds Recursion Depth in C++

huangapple go评论107阅读模式
英文:

Compile-Time Topological Sort Exceeds Recursion Depth in C++

问题

I've translated the code portion for you:

#include <tuple>
#include <iostream>
#include <type_traits>
#include <string_view>

template<typename SystemType, typename... DependencyTypes>
class SystemNode;

template<typename SystemType, typename... DependencyTypes>
class SystemNode<SystemType, std::tuple<DependencyTypes...>>
{
public:
    using system = SystemType;
    using dependencies = std::tuple<DependencyTypes...>;
};

template <typename System, typename Dependencies, size_t Degree>
struct NodeWithDegree
{
    using system = System;
    using dependencies = Dependencies;
    static constexpr size_t degree = Degree;
};

// (Rest of the code...)

int main()
{
    using tuple = GraphWithDegrees_t<
        Node10, Node9, Node8, Node7, Node6, Node5, Node4, Node3, Node2, Node1,
        Node11, Node12, Node13, Node14, Node15, Node16, Node17, Node18, Node19, Node20
    >;
    using SortedTuple = TopologicalSort_t<tuple>;
    printSystem<SortedTuple>();
    return 0;
}

Please note that translating code without understanding its functionality can lead to issues. Make sure you are familiar with the code's purpose and logic before using the translated version. If you have any questions or need further assistance, please let me know.

英文:

Hello Compile-Time Topological Sort Exceeds Recursion Depth in C++

I'm implementing a compile-time topological sort algorithm using C++ template metaprogramming. The algorithm is designed to sort a graph of dependencies between different systems in a game engine, but it could be used to sort any directed acyclic graph (DAG).

The graph is represented as a tuple of SystemNode objects, each of which represents a system and its dependencies. The algorithm sorts these nodes in a way that each node appears before its dependencies in the sorted list.

Breakdown

  1. GraphWithDegrees_t: This is the starting point of the algorithm. It takes a tuple of SystemNode objects and converts each node into a NodeWithDegree object, which is a node that also includes its degree (the number of nodes that depend on it). The degree of each node is calculated by the CountDependencies struct.

  2. TopologicalSort: This is the main part of the algorithm. It's a recursive struct that performs the topological sort. It works as follows:

    • Extracts all nodes with a degree of zero (i.e., nodes that no other nodes depend on). These nodes are added to the ExtractedSystems tuple, which holds the sorted nodes.

    • Collects the dependencies of the zero-degree nodes. This is done to know which nodes' degrees need to be decremented in the next step.

    • Removes the zero-degree nodes from the original tuple.

    • Decrements the degree of any nodes that depended on the removed nodes. This is done by checking if a node is in the dependencies collected in the previous step.

    • Recursively calls TopologicalSort with the updated tuple and the ExtractedSystems tuple.

    • When the tuple is empty (i.e., all nodes have been sorted), the recursion ends and the ExtractedSystems tuple is returned as the result.

  3. ExtractZeroDegree_t and RemoveZeroDegree_t: These structs are used to extract and remove zero-degree nodes from a tuple. They work by recursively iterating over the tuple and adding/removing nodes to/from a new tuple based on their degree.

  4. DecrementDegrees_t: This struct is used to decrement the degree of nodes that depend on a given set of nodes. It works by recursively iterating over the tuple and decrementing the degree of any nodes that are in the Dependencies tuple.

  5. AddSystemsToTuple_t: This struct is used to add the zero-degree nodes to the ExtractedSystems tuple. It works by recursively iterating over the tuple of zero-degree nodes and adding each node to the ExtractedSystems tuple.

Problem

The problem I'm facing is that the algorithm works fine for up to 15 types, but with 16 types, it exceeds the maximum recursion depth. I believe the recursion depth should be O(M), where M is the maximum degree count, so I'm not sure why it's failing with 16 types.

My questions are:

  1. Why does this algorithm exceed the maximum recursion depth with 16
    types?
  2. How can I modify it to handle more types?
  3. Given the complexity of this approach, would it be advisable to
    adopt a simpler approach to achieve the same result? If so, what
    alternatives could be recommended?

Please take me easy, I'm new here Compile-Time Topological Sort Exceeds Recursion Depth in C++

Source Code

You can also reproduce the probelm here: https://godbolt.org/z/T8cohdasr.

#include &lt;tuple&gt;
#include &lt;iostream&gt;
#include &lt;type_traits&gt;
#include &lt;string_view&gt;
template&lt;typename SystemType, typename... DependencyTypes&gt;
class SystemNode;
template&lt;typename SystemType, typename... DependencyTypes&gt;
class SystemNode&lt;SystemType, std::tuple&lt;DependencyTypes...&gt;&gt;
{
public:
using system = SystemType;
using dependencies = std::tuple&lt;DependencyTypes...&gt;;
};
template &lt;typename System, typename Dependencies, size_t Degree&gt;
struct NodeWithDegree 
{
using system = System;
using dependencies = Dependencies;
static constexpr size_t degree = Degree;
};
template &lt;typename Node, size_t Degree&gt;
struct ToNodeWithDegree
{
using type = NodeWithDegree&lt;typename Node::system, typename Node::dependencies, Degree&gt;;
};
template &lt;typename Node, size_t Degree&gt;
using ToNodeWithDegree_t = typename ToNodeWithDegree&lt;Node, Degree&gt;::type;
template &lt;typename T, typename Tuple&gt;
struct Contains;
template &lt;typename T, typename... Us&gt;
struct Contains&lt;T, std::tuple&lt;Us...&gt;&gt; : std::disjunction&lt;std::is_same&lt;T, Us&gt;...&gt; {};
template &lt;typename T, typename... Us&gt;
constexpr size_t Contains_v = Contains&lt;T, Us...&gt;::value;
template &lt;typename Node, typename Nodes&gt;
struct CountDependencies;
template &lt;typename Node, typename First, typename... Rest&gt;
struct CountDependencies&lt;Node, std::tuple&lt;First, Rest...&gt;&gt;
{
static constexpr size_t value = 
Contains_v&lt;typename Node::system, typename First::dependencies&gt; 
+ CountDependencies&lt;Node, std::tuple&lt;Rest...&gt;&gt;::value;
};
template &lt;typename Node&gt;
struct CountDependencies&lt;Node, std::tuple&lt;&gt;&gt;
{
static constexpr size_t value = 0;
};
template &lt;typename... Nodes&gt;
struct GraphWithDegrees
{
template&lt;typename Node&gt;
static constexpr size_t CountDependencies_v = CountDependencies&lt;Node, std::tuple&lt;Nodes...&gt;&gt;::value;
using type = std::tuple&lt;ToNodeWithDegree_t&lt;Nodes, CountDependencies_v&lt;Nodes&gt;&gt;...&gt;;
};
template &lt;typename... Nodes&gt;
using GraphWithDegrees_t = typename GraphWithDegrees&lt;Nodes...&gt;::type;
template &lt;typename NodesWithDegrees, typename ZeroDegreeNodes = std::tuple&lt;&gt;&gt;
struct ExtractZeroDegree;
template &lt;typename FirstNode, typename... RestNodes, typename... ZeroDegreeNodes&gt;
struct ExtractZeroDegree&lt;std::tuple&lt;FirstNode, RestNodes...&gt;, std::tuple&lt;ZeroDegreeNodes...&gt;&gt;
{
using type = std::conditional_t&lt;
FirstNode::degree == 0,
typename ExtractZeroDegree&lt;std::tuple&lt;RestNodes...&gt;, std::tuple&lt;ZeroDegreeNodes..., FirstNode&gt;&gt;::type,
typename ExtractZeroDegree&lt;std::tuple&lt;RestNodes...&gt;, std::tuple&lt;ZeroDegreeNodes...&gt;&gt;::type
&gt;;
};
template &lt;typename... ZeroDegreeNodes&gt;
struct ExtractZeroDegree&lt;std::tuple&lt;&gt;, std::tuple&lt;ZeroDegreeNodes...&gt;&gt;
{
using type = std::tuple&lt;ZeroDegreeNodes...&gt;; 
};
template &lt;typename NodesWithDegrees, typename ZeroDegreeNodes = std::tuple&lt;&gt;&gt;
using ExtractZeroDegree_t = typename ExtractZeroDegree&lt;NodesWithDegrees, ZeroDegreeNodes&gt;::type;
template &lt;typename NodesWithDegrees, typename NonZeroDegreeNodes = std::tuple&lt;&gt;&gt;
struct RemoveZeroDegree;
template &lt;typename FirstNode, typename... RestNodes, typename... NonZeroDegreeNodes&gt;
struct RemoveZeroDegree&lt;std::tuple&lt;FirstNode, RestNodes...&gt;, std::tuple&lt;NonZeroDegreeNodes...&gt;&gt;
{
using type = std::conditional_t&lt;
FirstNode::degree == 0,
typename RemoveZeroDegree&lt;std::tuple&lt;RestNodes...&gt;, std::tuple&lt;NonZeroDegreeNodes...&gt;&gt;::type,
typename RemoveZeroDegree&lt;std::tuple&lt;RestNodes...&gt;, std::tuple&lt;NonZeroDegreeNodes..., FirstNode&gt;&gt;::type
&gt;;
};
template &lt;typename... NonZeroDegreeNodes&gt;
struct RemoveZeroDegree&lt;std::tuple&lt;&gt;, std::tuple&lt;NonZeroDegreeNodes...&gt;&gt;
{
using type = std::tuple&lt;NonZeroDegreeNodes...&gt;; 
};
template &lt;typename NodesWithDegrees, typename NonZeroDegreeNodes = std::tuple&lt;&gt;&gt;
using RemoveZeroDegree_t = typename RemoveZeroDegree&lt;NodesWithDegrees, NonZeroDegreeNodes&gt;::type;
template &lt;typename T, typename Tuple&gt;
struct Prepend;
template &lt;typename T, typename... Ts&gt;
struct Prepend&lt;T, std::tuple&lt;Ts...&gt;&gt;
{
using type = std::tuple&lt;T, Ts...&gt;;
};
template &lt;typename T, typename Tuple&gt;
using Prepend_t = typename Prepend&lt;T, Tuple&gt;::type;
template &lt;typename T, typename Tuple&gt;
struct AddUnique;
template &lt;typename T&gt;
struct AddUnique&lt;T, std::tuple&lt;&gt;&gt;
{
using type = std::tuple&lt;T&gt;;
};
template &lt;typename T, typename First, typename... Rest&gt;
struct AddUnique&lt;T, std::tuple&lt;First, Rest...&gt;&gt;
{
using type = std::conditional_t&lt;
std::is_same_v&lt;T, First&gt;,
std::tuple&lt;First, Rest...&gt;,
Prepend_t&lt;First, typename AddUnique&lt;T, std::tuple&lt;Rest...&gt;&gt;::type&gt;
&gt;;
};
template &lt;typename T, typename Tuple&gt;
using AddUnique_t = typename AddUnique&lt;T, Tuple&gt;::type;
template &lt;typename Tuple1, typename Tuple2&gt;
struct AddUniqueElements;
template &lt;typename First, typename... Rest, typename Tuple2&gt;
struct AddUniqueElements&lt;std::tuple&lt;First, Rest...&gt;, Tuple2&gt;
{
using type = typename AddUniqueElements&lt;std::tuple&lt;Rest...&gt;, AddUnique_t&lt;First, Tuple2&gt;&gt;::type;
};
template &lt;typename Tuple2&gt;
struct AddUniqueElements&lt;std::tuple&lt;&gt;, Tuple2&gt;
{
using type = Tuple2;
};
template &lt;typename Tuple1, typename Tuple2&gt;
using AddUniqueElements_t = typename AddUniqueElements&lt;Tuple1, Tuple2&gt;::type;
template &lt;typename Nodes&gt;
struct CollectDependencies;
template &lt;typename FirstNode, typename... RestNodes&gt;
struct CollectDependencies&lt;std::tuple&lt;FirstNode, RestNodes...&gt;&gt;
{
using type = AddUniqueElements_t&lt;
typename FirstNode::dependencies,
typename CollectDependencies&lt;std::tuple&lt;RestNodes...&gt;&gt;::type
&gt;;
};
template &lt;&gt;
struct CollectDependencies&lt;std::tuple&lt;&gt;&gt;
{
using type = std::tuple&lt;&gt;;
};
template &lt;typename... Nodes&gt;
using CollectDependencies_t = typename CollectDependencies&lt;Nodes...&gt;::type;
template &lt;typename NodesWithDegrees, typename Dependencies&gt;
struct DecrementDegrees;
template &lt;typename FirstNode, typename... RestNodes, typename... Dependencies&gt;
struct DecrementDegrees&lt;std::tuple&lt;FirstNode, RestNodes...&gt;, std::tuple&lt;Dependencies...&gt;&gt;
{
using type = std::conditional_t&lt;
Contains_v&lt;typename FirstNode::system, std::tuple&lt;Dependencies...&gt;&gt;,
Prepend_t&lt;
NodeWithDegree&lt;
typename FirstNode::system, 
typename FirstNode::dependencies, 
FirstNode::degree - 1
&gt;, 
typename DecrementDegrees&lt;std::tuple&lt;RestNodes...&gt;, std::tuple&lt;Dependencies...&gt;&gt;::type
&gt;,
Prepend_t&lt;
FirstNode, 
typename DecrementDegrees&lt;std::tuple&lt;RestNodes...&gt;, std::tuple&lt;Dependencies...&gt;&gt;::type
&gt;
&gt;;
};
template &lt;typename... Dependencies&gt;
struct DecrementDegrees&lt;std::tuple&lt;&gt;, std::tuple&lt;Dependencies...&gt;&gt;
{
using type = std::tuple&lt;&gt;; 
};
template &lt;typename NodesWithDegrees, typename Dependencies&gt;
using DecrementDegrees_t = typename DecrementDegrees&lt;NodesWithDegrees, Dependencies&gt;::type;
template &lt;typename NodesWithDegrees, typename ExtractedSystems&gt;
struct AddSystemsToTuple;
template &lt;typename FirstNode, typename... RestNodes, typename... ExtractedSystems&gt;
struct AddSystemsToTuple&lt;std::tuple&lt;FirstNode, RestNodes...&gt;, std::tuple&lt;ExtractedSystems...&gt;&gt;
{
using nextTuple = std::tuple&lt;RestNodes...&gt;;
using newExtractedSystems = std::tuple&lt;typename FirstNode::system, ExtractedSystems...&gt;;
using type = typename AddSystemsToTuple&lt;nextTuple, newExtractedSystems&gt;::type;
};
template &lt;typename... ExtractedSystems&gt;
struct AddSystemsToTuple&lt;std::tuple&lt;&gt;, std::tuple&lt;ExtractedSystems...&gt;&gt;
{
using type = std::tuple&lt;ExtractedSystems...&gt;;
};
template &lt;typename NodesWithDegrees, typename ExtractedSystems&gt;
using AddSystemsToTuple_t = typename AddSystemsToTuple&lt;NodesWithDegrees, ExtractedSystems&gt;::type;
template &lt;typename SystemsWithDegrees, typename ExtractedSystems = std::tuple&lt;&gt;&gt;
struct TopologicalSort
{
using ZeroDegreeSystems = ExtractZeroDegree_t&lt;SystemsWithDegrees&gt;;
using NewExtractedSystems = AddSystemsToTuple_t&lt;ZeroDegreeSystems, ExtractedSystems&gt;;
using Dependencies = CollectDependencies_t&lt;ZeroDegreeSystems&gt;;
using RemainingSystems = RemoveZeroDegree_t&lt;SystemsWithDegrees&gt;;
using DecrementRemainingSystems = DecrementDegrees_t&lt;RemainingSystems, Dependencies&gt;;
using type = typename TopologicalSort&lt;DecrementRemainingSystems, NewExtractedSystems&gt;::type;
};
template &lt;typename ExtractedSystems&gt;
struct TopologicalSort&lt;std::tuple&lt;&gt;, ExtractedSystems&gt;
{
using type = ExtractedSystems;
};
template &lt;typename SystemsWithDegrees, typename ExtractedSystems = std::tuple&lt;&gt;&gt;
using TopologicalSort_t = typename TopologicalSort&lt;SystemsWithDegrees, ExtractedSystems&gt;::type;
template &lt;typename T&gt;
constexpr auto type_name() noexcept {
std::string_view name = &quot;Error: unsupported compiler&quot;, prefix, suffix;
#ifdef __clang__
name = __PRETTY_FUNCTION__;
prefix = &quot;auto type_name() [T = &quot;;
suffix = &quot;]&quot;;
#elif defined(__GNUC__)
name = __PRETTY_FUNCTION__;
prefix = &quot;constexpr auto type_name() [with T = &quot;;
suffix = &quot;]&quot;;
#elif defined(_MSC_VER)
name = __FUNCSIG__;
prefix = &quot;auto __cdecl type_name&lt;&quot;;
suffix = &quot;&gt;(void) noexcept&quot;;
#else
static_assert(false, &quot;Unsupported compiler!&quot;);
#endif
name.remove_prefix(prefix.size());
name.remove_suffix(suffix.size());
return name;
}
template &lt;typename T&gt;
void printSystem()
{
std::cout &lt;&lt; type_name&lt;T&gt;() &lt;&lt; &#39;\n&#39;;
}
struct System1 {};
struct System2 {};
struct System3 {};
struct System4 {};
struct System5 {};
struct System6 {};
struct System7 {};
struct System8 {};
struct System9 {};
struct System10 {};
struct System11 {};
struct System12 {};
struct System13 {};
struct System14 {};
struct System15 {};
struct System16 {};
struct System17 {};
struct System18 {};
struct System19 {};
struct System20 {};
using Node1 = SystemNode&lt;System1, std::tuple&lt;&gt;&gt;;
using Node2 = SystemNode&lt;System2, std::tuple&lt;System1&gt;&gt;;
using Node3 = SystemNode&lt;System3, std::tuple&lt;System2&gt;&gt;;
using Node4 = SystemNode&lt;System4, std::tuple&lt;System3&gt;&gt;;
using Node5 = SystemNode&lt;System5, std::tuple&lt;System4&gt;&gt;;
using Node6 = SystemNode&lt;System6, std::tuple&lt;System5&gt;&gt;;
using Node7 = SystemNode&lt;System7, std::tuple&lt;System6&gt;&gt;;
using Node8 = SystemNode&lt;System8, std::tuple&lt;System7&gt;&gt;;
using Node9 = SystemNode&lt;System9, std::tuple&lt;System8&gt;&gt;;
using Node10 = SystemNode&lt;System10, std::tuple&lt;System9&gt;&gt;;
using Node11 = SystemNode&lt;System11, std::tuple&lt;System10&gt;&gt;;
using Node12 = SystemNode&lt;System12, std::tuple&lt;System11&gt;&gt;;
using Node13 = SystemNode&lt;System13, std::tuple&lt;System12&gt;&gt;;
using Node14 = SystemNode&lt;System14, std::tuple&lt;System13&gt;&gt;;
using Node15 = SystemNode&lt;System15, std::tuple&lt;System14&gt;&gt;;
using Node16 = SystemNode&lt;System16, std::tuple&lt;System15&gt;&gt;;
using Node17 = SystemNode&lt;System17, std::tuple&lt;System16&gt;&gt;;
using Node18 = SystemNode&lt;System18, std::tuple&lt;System17&gt;&gt;;
using Node19 = SystemNode&lt;System19, std::tuple&lt;System18&gt;&gt;;
using Node20 = SystemNode&lt;System20, std::tuple&lt;System19&gt;&gt;;
int main()
{
using tuple = GraphWithDegrees_t&lt;
Node10, Node9, Node8, Node7, Node6, Node5, Node4, Node3, Node2, Node1, 
Node11, Node12, Node13, Node14, Node15, Node16, Node17, Node18, Node19, Node20
&gt;;
using SortedTuple = TopologicalSort_t&lt;tuple&gt;;
printSystem&lt;SortedTuple&gt;();
return 0;
}

Output:

terminate called after throwing an instance of &#39;std::bad_alloc&#39;
what():  std::bad_alloc```
</details>
# 答案1
**得分**: 4
您的编译器出现了内部错误/内存不足的情况。这并不是某种任意的嵌套模板实例化限制。
我在本地机器上成功编译了一个包含20个节点的版本。在使用gcc编译时大约需要20秒,使用clang编译时大约需要30秒。
然后我将节点数量增加到了50。编译过程使我的计算机(诚然,按今天的标准来看不是很强大)变得非常慢,大约20分钟后我中止了它。
因此,在实际应用中,将模板元编程推到如此远的程度可能并不是一个好主意。
<details>
<summary>英文:</summary>
Your compiler has an internal error/out of memory condition. It is not some kind of arbitrary nested template instantiation limit.
I was able to compile a version with 20 nodes on my machine locally. It took about 20 seconds with gcc and about 30 seconds with clang.
I then increased the number of nodes to 50. The compilation brought my computer (admittedly not very beefy by today&#39;s standards) to a crawl and I killed it after 20 minutes or so.
So in practice it&#39;s probably not a good idea to push template metaprogramming that far.
</details>

huangapple
  • 本文由 发表于 2023年8月5日 02:05:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76838256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定