gpt4 book ai didi

c++ - 为什么在以下情况下不需要对依赖类型使用 typename ?

转载 作者:行者123 更新时间:2023-12-01 17:35:54 27 4
gpt4 key购买 nike

我一直在阅读有关删除类型引用的内容,here .

它给出了以下示例:

#include <iostream> // std::cout
#include <type_traits> // std::is_same

template<class T1, class T2>
void print_is_same() {
std::cout << std::is_same<T1, T2>() << '\n';
}

int main() {
std::cout << std::boolalpha;

print_is_same<int, int>();
print_is_same<int, int &>();
print_is_same<int, int &&>();

print_is_same<int, std::remove_reference<int>::type>(); // Why not typename std::remove_reference<int>::type ?
print_is_same<int, std::remove_reference<int &>::type>();// Why not typename std::remove_reference<int &>::type ?
print_is_same<int, std::remove_reference<int &&>::type>();// Why not typename std::remove_reference<int &&>::type ?
}

type位于 std::remove_reference特征是依赖类型。

可能的实现

template< class T > struct remove_reference      {typedef T type;};
template< class T > struct remove_reference<T&> {typedef T type;};
template< class T > struct remove_reference<T&&> {typedef T type;};

但是为什么它不使用 typename std::remove_reference</*TYPE*/>::type

最佳答案

The types in the std::remove_reference traits are dependent types.

不,他们不是dependent names这里。模板参数已明确指定为 int , int&int&& 。因此,此时类型是已知的。

另一方面,如果您使用 std::remove_reference带有模板参数,例如

template <typename T>
void foo() {
print_is_same<int, typename std::remove_reference<T>::type>();
}

那么你必须使用 typename 告诉你std::remove_reference<T>::type是一种类型,因为您的表达式现在取决于模板参数 T .

关于c++ - 为什么在以下情况下不需要对依赖类型使用 typename ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58604511/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com