explanation

i was reading this section and have a question

http://www.cplusplus.com/doc/tutorial/functions2/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// template arguments
#include <iostream>
using namespace std;

template <class T, int N>
T fixed_multiply (T val)
{
  return val * N;
}

int main() {
  std::cout << fixed_multiply<int,2>(10) << '\n';
  std::cout << fixed_multiply<int,3>(10) << '\n';
}



all the way at the end of the page it states
For that same reason, the second template argument needs to be a constant expression (it cannot be passed a variable).
Where is it specified on the template that the second argument needs to be a constant? I cant see that int he code.
Where is it specified on the template that the second argument needs to be a constant?
In standard. All template arguments should be known in compile time.

Quote from page you linked:
the value of template parameters is determined on compile-time to generate a different instantiation of the function fixed_multiply, and thus the value of that argument is never passed during runtime
A non-type template argument of an integral type must be a constant expression; an expression that can be evaluated at compile time. This is a requirement; akin to the requirement that the size of an array must be an integral constant expression.

However, it can be a variable or an expression involving a variable or a function call (as long as it can be evaluated at compile time). See: http://en.cppreference.com/w/cpp/language/constant_expression

For an lvalue reference template parameter, the argument must be an lvalue with inkage, but it need not even be a reference to const.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

template < typename T, int& N >
T fixed_multiply( T val )
{
    int result = val * N ;
    N += 5 ;
    return result ;
}

int multiplier = 3 ;

int foo( int arg ) { return fixed_multiply<int,multiplier>(arg) ; }

int main()
{
  std::cout << foo(10) << '\n'; // 30
  std::cout << foo(10) << '\n'; // 80
  multiplier = -9 ;
  std::cout << foo(10) << '\n'; // -90
}

http://coliru.stacked-crooked.com/a/00e7e181fd290f44
Topic archived. No new replies allowed.