Reputation: 41
template <int ns, int id>
class Bar
{
public:
static int value;
};
template <int ns, int id>
int Bar<ns, id>::value = 0;
class Foo
{
public:
template <int ns, int id>
static int GetNextValue()
{
++Bar<ns, id>::value;
return Bar<ns, id>::value;
}
};
class Baz
{
public:
Baz(int value)
: value(value)
{
}
void PrintBaz();
private:
int value;
};
This works fine when called like:
Baz baz(Foo::GetNextValue<1, 1>());
I need this code to support the following.
int ns = 1;
int id = 5;
Baz baz(Foo::GetNextValue<ns, id>());
Compilation for this code fails understandably. Is there a way to have template meta-programming support runtime variable values?
Pointer to solution for this problem by any other method will also be helpful.
Upvotes: 1
Views: 692
Reputation: 16156
A template meta programm "runs" during compilation. So every input into it must be known at compile time.
Think of this:
template<int N>
int get(void) {
return N;
}
This creates a completely new function on each instantiation with a different value for N
. So if the passed value of some instantiation isn't known at compile time, this would mean that the new function had to be generated during runtime. For this to work you'd need the compiler to be part of your final application. It might seem simple in this case, but there are pretty complex meta programms out there.
Moreover, even the syntax of C++ depends on the results of some meta programms:
template<bool = true>
struct switch {
template<int>
using thing = int;
};
template<>
struct switch<false> {
int thing = 21;
}
switch<META>::thing<42>(21);
// bool result of comparisons: 21 < 42 > 21
// or int result from cast: 21
Upvotes: 0
Reputation: 14077
The simple answer is no, templates are a compile time construct. You might want to consider constexpr
functions if you need code that can be evaluated at compile time or runtime.
Upvotes: 2