C1202: recursive type or function dependency context too complex

Viewed 208

I tried to write a function that would call back with every permutation of size n:

template<typename F>
void permutationsCallback(int n, F f) {
    if (n == 1) {
        f(std::vector<int>{0});
    }
    else {
        permutationsCallback(n - 1, [n, &f](std::vector<int> p) {
            p.emplace_back(n - 1);
            f(p);
            while (--p.back() >= 0) {
                for (int k = 0; k < n - 1; k++) {
                    p[k] += p[k] == p.back();
                }
                f(p);
            }
        });
    }
}

(For example I want permutationsCallback(3, f) to call f({0,1,2}, f({0,2,1}), f({1,2,0}), f({1,0,2}), f({2,0,1}), f({2,1,0}).)

but on compilation with MCSV I get error

fatal error C1202: recursive type or function dependency context too complex

How can I fix this?

1 Answers

There is an infinite recursion inside the template. Even if you know the else-block won't be called at runtime, at compile time, the compiler needs to know what code would have gone into the else block, endlessly.

You can for example consider making n a template parameter instead, and implement the 0 case, like MSVC explains on their page for this error message:

https://docs.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/fatal-error-c1202?view=msvc-160

For reference from link above:

// C1202b.cpp
// compile with: /c
template<int n>
class Factorial : public Factorial<n-1> {
public:
   operator int () {
      return Factorial <n-1>::operator int () * n;
   }
};

template <>
class Factorial<0> {
public:
   operator int () {
      return 1;
   }
};

Factorial<7> facSeven;
Related