C ++: combining const with template arguments

The following example works when I manually replace Twirh char *, but why it doesn't work, 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*]'
+3
source share
6 answers

Try converting to const T &. In addition, in these cases, you should allow the compiler to automatically output the template argument and not specify it.

0
source

Substitution Twith char*gives a pointer constto char, and is cdeclared as a pointer to const char.

, . , Boost Call Traits, .

+10

, const (char *) ( T char *), , , const char * (const char) *, .. , .

+2

, , , T = char* , , (c), char* ( : a const char*) .

:

  • const_cast c
  • A<const char *> a(c);
  • const

- # 3. , , "", : , A, . , , , , T const.

+2

c, .

, , const. const , T_t, const ... , .

+1

A(const char* _t), A( (const char) *t). const char. char* , A( const (char *t)) const char.

In other words, I think that you have the same problem that is mentioned in the article “Summer Madness of the Summer Sun” , except for the template parameters instead of typedefs.

+1
source

Source: https://habr.com/ru/post/1745186/


All Articles