template <typename T>
// 1:
void compare(T, T) {}
int main{
compare("123", "45");
}
// T is const char *
// 2:
void compare(T *, T *) {}
// T is const char
// 3:
void compare(const T *, const T *) {}
// T is char
// 4:
void compare(const T, const T) {}
// T is const char *
1:
我的问题是根据 1,2,3 的模式,我完全可以理解
为什么 T 变成了它的样子。而第 4 个代码中的 T 不是我推测的 char *
。
2:
以及为什么第一个代码和第四个代码产生相同类型的 T。
3:
我可以使用 const char *
的 reference
作为 compare
中的参数吗
最佳答案
My question is according to the pattern of 1,2,3 which I can totally understand why T becomes how it looks like.Whereas T in the 4'th code is not char * which I presumed.
因为您被误导识别出错误的模式。这是为什么“领先的 const 具有误导性”的一个例子。模板不像宏,const
放在左边并不意味着它适用于 char
。它适用于整个参数类型,并且由于参数将是一个指针(考虑到文字作为参数给出),合成函数将是这样的:
void compare(char const* const, char const* const) {}
这就是为什么许多 C++ 程序员(包括我自己)喜欢 cv-qualifers 的不同位置。你的选项 3 和 4 应该是这样写的:
void compare(T const *, T const *) {}
// T is char
// 4:
void compare(T const, T const ) {}
// T is const char *
它更一致,因为 const
总是适用于它左边的东西(如果有东西,否则有一个异常,一个令人困惑的异常)。而且它还非常清楚(好吧,IMO 无论如何)当推导结束时什么将是 const。
关于c++ - 在模板参数推导过程中会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55205040/