你想要的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
在運行時,你可以用make在編譯時檢查static_assert
static_assert(is_same<decltype(C<int>::method()), int&>::value, "");
static_assert(is_same<decltype(C<int const>::method()), int>::value, "");
Live demo