Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: combine const with template arguments

The following example is working when I manualy replace T wirh char *, but why is not working as it is:

template <typename T>
class A{
  public:
    A(const T _t) { }
};

int main(){
  const char * c = "asdf";
  A<char *> a(c);
}

When compiling with gcc, I get this error:

test.cpp: In function 'int main()':
test.cpp:10: error: invalid conversion from 'const char*' to 'char*'
test.cpp:10: error:   initializing argument 1 of 'A<T>::A(T) [with T = char*]'
like image 577
Allan Avatar asked Dec 06 '22 02:12

Allan


2 Answers

Substituting T with char* gives a const pointer to char, while c is declared as a pointer to const char.

A solution would be to take pointers and integral types by value and class types by const reference. If you can, use Boost Call Traits which solves these kinds of problems for you.

like image 186
Georg Fritzsche Avatar answered Dec 08 '22 00:12

Georg Fritzsche


I guess it's because your function expects const (char *) (since T is char *), i.e. you can't change the address it points to, while const char * stands for (const char) *, i.e. you can't change the value on the place the pointer points to.

like image 31
petersohn Avatar answered Dec 07 '22 23:12

petersohn