Last active
December 12, 2019 13:54
-
-
Save disconnect3d/13c2d035bb31b244df14 to your computer and use it in GitHub Desktop.
C++ template for loop which use loop counter as template argument
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <array> | |
template<size_t c> | |
struct ForLoop { | |
template<template <size_t> class Func> | |
static void iterate() { | |
Func<c>()(); | |
ForLoop<c-1>::template iterate<Func>(); | |
} | |
}; | |
template<> | |
struct ForLoop<0> { | |
template<template <size_t> class Func> | |
static void iterate() { | |
Func<0>()(); | |
} | |
}; | |
template <size_t size> | |
struct Foo { | |
void operator()() { | |
std::array<int, size> arr; | |
std::cout << "Array size: " << arr.size() << std::endl; | |
} | |
}; | |
int main() { | |
ForLoop<4>::iterate<Foo>(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Useful materials:
http://stackoverflow.com/questions/10871100/pass-a-function-as-an-explicit-template-parameter
So the
Foo
can't be just template function - instead it must be a struct.http://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords
The
template
is required here, because it is a dependent template