C++:结合 const 与模板参数 [英] C++: combine const with template arguments

查看:23
本文介绍了C++:结合 const 与模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下示例在我手动替换 T wirh char * 时有效,但为什么不能按原样工作:

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);
}

使用 gcc 编译时,我收到此错误:

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

推荐答案

尝试转换为 const T&.此外,在这些情况下,您应该让编译器自动推导出模板参数,而不是指定它.

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

这篇关于C++:结合 const 与模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆