Reputation: 1506
I have learned that:
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.
Upvotes: 1
Views: 162
Reputation: 31
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.
Upvotes: 0
Reputation: 6800
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
Upvotes: 1