我有一个接受类型 T
的类模板。它有一个方法。我希望此方法返回类型 T
如果它是 const
和 T&
如果它是非 const
。
template<typename T>
class C
{
static typename add_reference_if_non_const<T>::type method();
};
int main()
{
assert( is_same<result_of<C<int>::method()>::type, int&>::value );
assert( is_same<result_of<C<const int>::method()>::type, const int>::value );
}
我该怎么做?
最佳答案
你想要 C<int const>::method()
的返回类型成为int const
, 但是 top-level cv qualifiers are ignored on function return types .无论如何,因为method()
返回 T
的拷贝,你真的在乎你回来吗T const
而不是 T
?
鉴于此,我认为您想要的是以下内容
using add_reference_if_non_const =
typename std::conditional<std::is_const<T>{},
typename std::remove_const<T>::type,
typename std::add_lvalue_reference<T>::type
>::type;
static add_reference_if_non_const method();
你可以替换typename std::remove_const<T>::type
与 T
如果你想返回 T const
什么时候T
是一个类类型。
下一个问题是 result_of
适用于类型参数;您在问题中遇到的是 C::method
的函数调用.你需要使用
result_of<decltype(&C<int>::method)()>::type
但是因为你需要使用 decltype
无论如何,你可以完全取消 result_of
.
decltype(C<int>::method())
最后,你不需要 assert
在运行时,您可以在编译时使用 static_assert
进行检查
static_assert( is_same<decltype(C<int>::method()), int&>::value, "");
static_assert( is_same<decltype(C<int const>::method()), int>::value, "" );
关于C++ type_traits 模板,如果不是 const,则添加引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33199101/