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.
相关文章