我有以下功能(仅用于重现问题):
template <typename KeyT>
void func(const KeyT cptr) {
std::cout << typeid(KeyT).name() << std::endl;
}
我想用字符串文字来调用它,如下所示:
func<char*>("literal");
但是,我最终得到以下警告:
warning: ISO C++11 does not allow conversion from string literal to 'char *' [-Wc++11-compat-deprecated-writable-strings]
我特别需要使用 char*
作为我的 Key 类型,我期望 TAD
将 param type
视为 const char*
整体,因为我没有引用它。
警告来自 clang
和 g++
编译器。
这里的param type
是怎么推导出来的?
提前致谢。
最佳答案
I was expecting
TAD
to consider the param type as const char* ...
How is the param type being deduced here ?
template <typename KeyT>
void func(const KeyT cptr)
注意 const
是 KeyT
本身的限定符,这意味着如果 KeyT
是一个指针,那么 cptr
将是一个 const 指针,而不是指向 const 的指针。
"literal"
是 const char[8]
类型的字符串字面量,可能会衰减为 const char*
。那么KeyT
可能会被推导出为const char*
,那么cptr
的类型将会是const char* const
。
您将模板参数类型指定为 char*
,然后将 cptr
设为 char* const
。但从 C++11 开始,不允许将字符串文字隐式转换为 char*
,因为文字是 const
。
为什么需要模板参数类型为char*
?在函数内部修改它?请注意,修改字符串文字会导致 UB。您可以将 char 数组传递给它,例如:
char my_chararray[] = "literal";
func<char*>(my_chararray); // or just func(my_chararray);
关于c++ - 'char*'的模板参数推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37642048/