#include <iostream>
template < typename Var, typename Value >
void Store( Var& var, Value value ) {
var = value;
}
int main( int argc, char* argv[] ) {
char* a;
Store( a, "Hello!" );
std::cout << a << std::endl;
std::cin.get();
return 0;
}
Store() assigns the value of the second parameter to the first one.
It gives the following errors (Dev-Cpp):
In function `void Store(Var&, Value) [with Var = char*, Value = const char*]':
10 instantiated from here
5 invalid conversion from `const char*' to `char*'
That would mean that the "Hello!" argument is const char* . Is that true? And how do I solve the problem?
String literals are pointers to arrays of constant characters ["char const *"]. Because of this, in your function "Store( )", you're attempting to copy a pointer to constant data ["value"] to a pointer to non-constant data ["a"]. This violates const-correctness, and is therefore not allowed.
That said, your "Store( )" function, once instantiated (type-deduction), becomes this:
1 2 3 4
void Store(char *&var, charconst *value)
{
var = value; // Error; cannot convert from "char *" to "char const *".
}
Fransje wrote:
"If I do it like this, it works:"
1 2
char* a;
char* b = "Hello!";
Don't do that. Here, your giving "b" the address of constant data, without respecting the constness of the string literal. Attempting to modify the string in any form will result in a run-time termination.
1) Copy "value" into "var" using "strcpy( )". This isn't exactly safe because "var" may well be pointing to unknown memory; writing to that memory could prove problematic.