1

I never did template programming. What I need is the following: depending on certain integer (user input), my template should determine a type. Here is my template:

template<int T> struct abcd {};

template<>
struct abcd<6> { typedef double type_t; };
template<>
struct abcd<5> { typedef float type_t; };
template<>
struct abcd<0> { typedef unsigned char type_t; };enter code here

In certain function I want to use my template like this:

void foo(int i, int m)
{
    const int j = i;
    // Assume elements of A can be accessed as A.at<dataType>(location)
    int a = A<abcd<j>::type_t>(m)
   //do something.. 
}

This is showing error cannot appear in a constant-expression. Please tell me what I am doing wrong and what can be a solution. Note that if I put const int j = 5 or any other relevant int instead of const int j = i, it is working fine. That is confusing me.

2
  • 1
    Do you know about template instantiation? If no, read about it. If yes, think about this: How could a compiler possibly instantiate those templates?
    – marc
    Jan 27, 2015 at 20:18
  • We can hardly teach you the substantial concept of templates. You need a book.
    – Columbo
    Jan 27, 2015 at 20:20

3 Answers 3

2

abcd<j> has to be instantiated at compile time, so j has to be a constant expression. In your case, you don't know j at compile time, since it is obtained from the parameter of the function foo, and that's why the error.

Parameters of a function are not considered constant expressions, even if you invoke foo(6,...). The argument 6, although known at compile time, is bounded to the parameter i, which is NOT by itself a constant expression.

You may have though that you have something like

foo(constexpr i, int m)

but such syntax is illegal, that is, function parameters cannot be constant expressions. I do not know exactly why the standard does not allow such constructions, and I'm more than willing to hear any opinions.

A workaround is to declare foo taking i as a template, like

template<int i>
void foo(int m)
{
    const int j = i;
    // now can use j as a constant expression
}

and invoke it as e.g.

f<5>(...);
0
1

the value of j must be known during compilation time.

1

Please note that template parameters need to be known at compile time. You've declared j as a constant, but it is not known at compile time

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.