1

I have learned that:

  • Nontype template parameters carry some restrictions. In general, they may be constant integral values (including enumerations) or pointers to objects with external linkage.

So i made following code

1.

 template <char const* name> class MyClass { … }; char const* s = "hello"; MyClass<s> x; // ERROR: 

This code didn't work and produce error 's' is not a valid template argument

My second code also didn't work

2.

template <char const* name> class MyClass { … }; extern char const *s = "hello"; MyClass<s> x; //error 's' is not a valid template argument` 

But strangely this code is fine

3.

template <char const* name> class MyClass { … }; extern char const s[] = "hello"; MyClass<s> x; // OK 

please tell what is happening in all of these three codes??

also tell how to correct errors to make other two codes working also.

1
  • 2
    Ah, the old const * vs * const chestnut... Commented Feb 7, 2012 at 8:20

2 Answers 2

1

From here: "Non-type template argument provided within a template argument list is an expression whose value can be determined at compile time".

You get a problem because your char pointer is not really constant in the first two examples. Have a look at this short example:

int main() { char const *c = "foor"; std::cout << "c: " << c << std::endl; c = "bar"; std::cout << "c: " << c << std::endl; } 

Which will give you

c: foo c: bar 
Sign up to request clarification or add additional context in comments.

6 Comments

The C-style cast is totally superfluous. c is not const, it just points to a const array of char.
@ezdazuzena : as You said i get a problem because char pointer is not really constant in the first two examples.But making them constant still doesn't work .Compiler shows same error. Also what do you mean by "Non-type template argument provided within a template argument list is an expression whose value can be determined at compile time"."and how these are related to only int and pointer to ojects with external linkage .why not floats etc .
@10001001058: it means, that you can give a variable. It must be fixed at compile time.
@ezdazuzena: then why this not valid for floats?? Also my codes aren't working even after making my pointers constant .
@10001001058: As you said in the question: must be "constant integral values or pointers". float is neither.
|
0

I think the problem is here: even

const char * const p="hello";

only define a pointer variable which stores the address of a memory, the value of the memory cannot be determined when compilation. but

const char pp[]="hello";

the compiler will know when compile the memory is "hello", not a pointer to somewhere else. that's why

printf(" p=%p, &p=%p\n", p, &p);

will get the same value. but

printf("pp=%p, &pp=%p\n", pp, &pp);

will not show the same value.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.