My code is something like this:
开发者_运维问答 // ... code
template <int i>
int modifyparameter()
{
i = i++;
return i;
}
// ... some more code
int main()
{
int answer = modifyparameter<5>();
cout << answer; //expecting 6
}
But I am getting errors. What have I done wrong?
i
is the name of an int value, and you cannot modify values. You probably want one of these:
template <typename Number>
Number functional(Number x)
{
return x + 1;
}
template <typename Number>
Number& side_effect(Number& x)
{
return ++x;
}
i
is not an lvalue
, so i++
is illegal.
14.1/5
says.
A non-type non-reference template-parameter is not an lvalue. It shall not be assigned to or in any other way have its value changed.
Post-increment operator (++
) requires an lvalue
as an operand.
Try:
template <int i>
int modifyparameter()
{
int copy_of_i = i;
copy_of_i++;
return copy_of_i;
}
There's nothing you can do to modify i
itself, template parameters are compile-time constants. However, you could make it act as if I was being modified by using a variable with static lifetime:
template <int i>
int modifyparameter()
{
static int copy_of_i = i;
copy_of_i++;
return copy_of_i;
}
While it's not asked for, this seems to cry out for a compile-time solution:
template< int I >
struct increment { static const int result = I+1; };
std::cout << increment<41>::result << '\n';
That struct
is what's called a meta-function. Yes, it's a struct, but it's used (at compile-time) like a function: you call it, passing a parameter, and you get back a result. The syntax is hilarious, but that's because nobody actually planned to do this; the possibility was discovered (more or less) by accident.
Doing this at compile-time has the advantage that the result is a compile-time constant and can be used as such:
int my_array[increment<7>::result]; // array of 7+1 ints
Of course, defining an array like this is nonsense. Just as in run-time algorithms, incrementing is usually just one operation of an algorithm that computes something more complex.
精彩评论