就像std::reference_wrapper
在幕后使用指针来存储“引用”一样,我正在尝试使用以下代码做类似的事情。
#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
参考参数的返回为真?