c++ - 在模板参数推导过程中会发生什么?

标签 c++ templates

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/

相关文章:

给定模板类的 C++ 类模板专门化

c++ - 如何通过类模板的参数指定一个成员函数(在类内部更好)?

c++ - shared_ptr 上的 static_cast 导致未定义的行为

c++ - 这种链接异常的实现是如何工作的?

c++ - 从 C++ 中的模板参数继承时无法访问基类的枚举

c++ - C++模板错误: ‘=’ token 之前缺少模板参数

C++ 预期左大括号以及重新定义错误

c++ - gdb 远程调试缓存远程目标

c++ - 在 float 组上使用 mpf_set_ui 停止输出 (GMP c++)

javascript - Reactive Meteor Templates and Deps Dependency——当另一个模板改变或重新渲染时更新模板