0

I'm attempting to write a template meta-programming program to implement a Binary Tree struct, with a method "Map" that applies a metafunction to every node in the tree. For instance, if I implementing a metafunction, Double:

template <int i>
struct Double
{
    static constexpr int value = 2 * i;
};

Then the following code would result in a Binary Tree equal to "BinaryTree<4, Leaf(2), Leaf(6)>":

using T = BinaryTreeNode<2, Leaf<1>, Leaf<3>>;
T::Map<Double>::type;

Here is my implementation:

template <int i, typename LEFT, typename RIGHT>
struct BinaryTreeNode
{
    template<template <int> typename F>
    struct Map
    {
        static constexpr int newHead = F<i>::value;
        using newLeft = LEFT::Map<F>::type;
        using newRight = RIGHT::Map<F>::type;
        using type = BinaryTreeNode<newHead, newLeft, newRight>;
    };
};

template <int i>
struct Leaf
{
    template<template <int> typename F>
    struct Map
    {
        using type = Leaf<F<i>::value>;
    };
};

I'm having trouble getting it to compile: I get a bunch of issues to with "missing ';' before '<'".

I imagine it is trying to use '<' to mean 'less than', rather than to get a template argument. However, I've tried adding ".template" and "typename" in various different places and none seem to work. Interestingly, if I move the Map meta-function out of the struct and have it take the tree as a parameter, that then works. I'd like to get to the bottom of this inconsistency.

  • 1
    GCC's error messages seem to point straight at missing `typename` before `LEFT::Map::type` and `RIGHT::Map::type`. With those added, your code compiles. The reason is that those are [dependent types](https://en.cppreference.com/w/cpp/language/dependent_name); the compiler does not know at template declaration time wether `Map` will even have a `::type`, and if so it could either be a typename or a static member. – G. Sliepen May 18 '22 at 21:58
  • 1
    Thanks for the quick response - for me adding "::template" between LEFT and Map fixed the issue. I didn't get that error message in MSVC, I'll try testing issues like this in compiler explorer in the future. – Anthony Poole May 18 '22 at 22:19

0 Answers0