[英]Get the type of & for built-in and operator&()?
Edit: The answer I've marked below isn't 100% correct, that's actually in a comment: using TPtr = decltype(&std::declval<T&>());
编辑:我在下面标记的答案不是100%正确,实际上是在注释中:
using TPtr = decltype(&std::declval<T&>());
I'm trying to use std::conditional<>
to get the type of &T
, where T
may have operator&()
, or not. 我正在尝试使用
std::conditional<>
来获取&T
的类型,其中T
可能具有operator&()
,或者没有。
The simple solution is to not even try, instead specify another template argument: 一个简单的解决方案是什至不尝试,而是指定另一个模板参数:
struct Foo
{
int operator&() { return 314; }
};
struct Bar { };
template <typename T, typename TPtr = T*>
struct A
{
T& _t;
A(T& t) : _t(t) {}
TPtr data() {
return &_t;
}
};
where client code is then 客户端代码在哪里
Foo foo;
A<Foo, int> aFoo(foo);
int pFooData = aFoo.data();
Bar bar;
A<Bar> aBar(bar);
Bar* pBarData = aBar.data();
But what I'd rather write is something like: 但是我想写的是这样的:
template <typename T>
struct B
{
using TPtr = typename std::conditional<has_operator_address_of<T>::value, typename std::result_of<decltype(T::operator&)&()>::type, T*>::type;
T& _t;
B(T& t) : _t(t) {}
TPtr data() {
return &t;
}
};
where has_operator_address_of
is modeled after is_call_possible
. has_operator_address_of
是在is_call_possible
之后is_call_possible
。 Client code is then 然后是客户代码
B<Foo> bFoo(foo); // no need to second template argument
pFooData = bFoo.data();
but then the class without operator&()
fails to compile: 但是没有
operator&()
的类无法编译:
B<Bar> bBar(bar);
pBarData = bBar.data();
It seems that conditional
wants to compile both template arguments, so compilation fails when T
doesn't have operator&()
. 似乎
conditional
语句要编译两个模板参数,因此当T
没有operator&()
时,编译将失败。 I've tried sprinkling std::enable_if
around, but to no avail. 我曾尝试在周围撒上
std::enable_if
,但无济于事。
You can use decltype
and declval
, with a little hackery to force an lvalue to be passed to the &
operator (which is required): 您可以使用
decltype
和declval
,并带有一些小declval
以强制将左值传递给&
运算符(这是必需的):
Start with #include <utility>
and define the following helper function: 从
#include <utility>
并定义以下帮助器函数:
template <typename T>
T& as_lvalue(T&& val)
{
return val;
}
Then: 然后:
using TPtr = decltype(&as_lvalue(std::declval<T>()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.