我正在使用C ++ 17。我有如下代码:
#include <type_traits>
template <typename T>
struct Fooer
{
Fooer (T & fooable)
{
fooable . foo ();
}
};
template <typename T>
Fooer (T & fooable) -> Fooer <T>;
struct Fooable
{
private:
void
foo ();
friend struct Fooer <Fooable>;
};
struct NotFooable
{
};
我想实现一个类型特征,该特征可以判断类型是否为'Fooable'。
我无法检查类型上是否有方法foo ()
,因为它是私有方法。这也没有告诉我Fooer
的构造函数是否可以调用该方法。
// Checking for the foo method doesn't work.
template <typename T, typename = void>
struct HasFoo;
template <typename T, typename>
struct HasFoo : std::false_type
{
};
template <typename T>
struct HasFoo
<
T,
std::enable_if_t
<
std::is_convertible_v <decltype (std::declval <T> () . foo ()), void>
>
>
: std::true_type
{
};
// Both of these assertions fail.
static_assert (HasFoo <Fooable>::value);
static_assert (HasFoo <NotFooable>::value);
我也无法检查Fooer <T>
是否可通过std::is_constructible
构造,因为std::is_constructible
不会检查构造函数definition是否格式正确,仅表达式Fooer <T> fooer (std::declval <T> ())
。
// Checking constructibility doesn't work either.
template <typename T, typename = void>
struct CanMakeFooer;
template <typename T, typename>
struct CanMakeFooer : std::false_type
{
};
template <typename T>
struct CanMakeFooer
<
T,
std::enable_if_t <std::is_constructible_v <Fooer <T>, T &>>
>
: std::true_type
{
};
// Neither of these assertions fail.
static_assert (CanMakeFooer <Fooable>::value);
static_assert (CanMakeFooer <NotFooable>::value);
如果我实际上尝试调用构造函数,虽然没有使我更接近实现类型特征,但我得到了我期望的错误。
void
createFooer ()
{
Fooable fooable;
NotFooable not_fooable;
// This works fine.
{ Fooer fooer (fooable); }
// This correctly generates the compiler error: no member named 'foo' in
// 'NotFooable'
{ Fooer fooer (not_fooable); }
}
[我想避免将类型特征声明为Fooable类型的朋友,并且我想避免公开'foo'。
如果我能以某种方式使类型特征检查函数或构造函数的definition的格式是否正确,我可以很容易地实现此类型特征,但是我不知道该怎么做,我可以在互联网上找不到此类事例。
可以做我想做的吗?我该怎么做?
我对您的HasFoo使用了类似的方法,但是使用函数而不是结构,并且按预期方式工作。
Fooer (T& fooable)
{
if constexpr (has_foo<T>(0)) {
cout << "Yes foo" << endl;
fooable.foo();
}
else {
cout << "No foo" << endl;
}
}
template<class Y>
static constexpr auto has_foo(Y*) -> decltype(std::declval<Y>().foo(), bool()) {
return true;
}
template<class Y>
static constexpr bool has_foo(...) {
return false;
}