像std::reference_wrapper
使用指針下方的指針來存儲「引用」,我試圖做類似於下面的代碼。std :: enable_if與std :: is_reference無法編譯
#include <type_traits>
struct Foo
{
void* _ptr;
template<typename T>
Foo(T val,
typename std::enable_if
<
std::is_reference<T>::value,
void
>::type* = nullptr)
: _ptr(&val)
{ }
};
int main()
{
int i = 0;
int& l = i;
Foo u2(l);
return 0;
}
然而,這無法編譯:
CXX main.cpp
main.cpp: In function ‘int main()’:
main.cpp:23:13: error: no matching function for call to ‘Foo::Foo(int&)’
main.cpp:23:13: note: candidates are:
main.cpp:8:5: note: template<class T> Foo::Foo(T, typename std::enable_if<std::is_reference<_Tp>::value, void>::type*)
main.cpp:8:5: note: template argument deduction/substitution failed:
main.cpp: In substitution of ‘template<class T> Foo::Foo(T, typename std::enable_if<std::is_reference<_Tp>::value, void>::type*) [with T = int]’:
main.cpp:23:13: required from here
main.cpp:8:5: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
main.cpp:3:8: note: constexpr Foo::Foo(const Foo&)
main.cpp:3:8: note: no known conversion for argument 1 from ‘int’ to ‘const Foo&’
main.cpp:3:8: note: constexpr Foo::Foo(Foo&&)
main.cpp:3:8: note: no known conversion for argument 1 from ‘int’ to ‘Foo&&’
我怎樣才能爲參考參數enable_if
回是真的嗎?
顯而易見的答案是在_is_reference &&!is_integral_上進行條件化,並且與之相反,它的工作原理但不是一個好的答案... –
@ K-ballo我已簡化了我的問題,並將編輯問題以更加準確反射問題 - 這是如何讓'enable_if對引用有效 –