已知以下函数指针有不同的类型:
void foo_int_ref(int&);
void foo_const_int_ref(const int&);
static_assert(
!std::is_same<
decltype(foo_int_ref),
decltype(foo_const_int_ref)
>::value,
"Types should be different");
让我们考虑这个概括:
template<typename T>
void foo(T t) {}
template<typename T>
struct ref_vs_const_ref {
typedef decltype(foo<T>) foo_T;
typedef decltype(foo<const T>) foo_const_T;
};
using int_ref_vs_const_ref = ref_vs_const_ref<int&>;
static_assert(
!std::is_same<
typename int_ref_vs_const_ref::foo_T,
typename int_ref_vs_const_ref::foo_const_T
>::value,
"Types should be different"); // -- it fails
最后一个断言失败。由于某些原因,const
丢失了 foo_const_T
。但是为什么?
最佳答案
值参数的 const
不会影响任何形状或形式的签名。从非模板声明中删除引用时也是如此。 const
只影响函数定义中参数的使用。如果您添加对类型的引用或指针,事情就会发生变化,const
会影响函数的类型。
在您的嵌套类型中,T
是应用了 const
的 int&
。但是,T&
和T& const
也是相同的类型。我猜你的困惑源于你不明智地将 const
放置在左侧:const
更多地应用于顶级实体。
关于c++ - 为什么 const 在这个模板结构中丢失了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47813732/