c++templatesconstantsconst-correctnessc++-templates

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*]'

Solution

  • Try converting to const T&. Also, in these cases, you should let the compiler automatically deduce the template argument, and not specify it.