像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对引用有效 –