【发布时间】:2019-01-30 15:32:41
【问题描述】:
我写了一个程序来看看,字符串字面量是如何在模板函数中推导出来的。
#include <iostream>
#include <string>
#include <type_traits>
template<typename T> void passByValue(T by_value)
{
std::cout << std::is_same_v<char const*, decltype(by_value)> << std::endl; // okay
}
template<typename T> void passByReferance(T &by_ref)
{
std::cout << std::is_same_v<char const*, std::remove_reference_t<decltype(by_ref)>> << std::endl;
}
template<typename T> void passByConstRef(const T &const_ref)
{
std::cout << std::is_same_v<char const*, std::remove_const_t<std::remove_reference_t<decltype(const_ref)>>> << std::endl;
}
int main()
{
std::cout << std::boolalpha;
passByValue("string"); // true: good
passByReferance("string");// false ??
passByConstRef("string"); // false ??
return 0;
}
事实证明,只有 passByValue 的字符串字面量才推导出为 const char* 类型。
在其他两种情况下(passByReference 和 passByConstRef),如果我们应用到推导的参数 std::remove_reference_t 和 std::remove_const_t,我想得到的是const char*,对吗?
当我使用 std::decay_t 进行完全衰减时得到类型匹配,这是为什么呢?
【问题讨论】:
-
答案涵盖了所有细节。如果您需要更好地了解类型,可以在此处使用帮助程序:godbolt.org/z/AqTA0e
-
@balki 太好了:您的代码演示了机器的视图。你能把它贴在答案部分吗?至少我可以给你竖起大拇指。
标签: c++ templates type-deduction