【发布时间】:2016-02-27 11:46:47
【问题描述】:
我在玩proposal of standard library support for the C++ detection idiom。它是一个类似于 trait 的元函数,用于确定类型 T 是否具有名为 T::type 的类型成员或具有特定签名的成员函数,例如:
#include <iostream>
template<class...>
using void_t = void;
template<class, template<class> class, class = void_t<>>
struct detect : std::false_type { };
template<class T, template<class> class Operation>
struct detect<T, Operation, void_t<Operation<T>>> : std::true_type { };
template<class T>
using bar_t = decltype(std::declval<T>().bar());
template<class T>
using bar_int_t = decltype(std::declval<T>().bar(0));
template<class T>
using bar_string_t = decltype(std::declval<T>().bar(""));
struct foo
{
int bar() { return 0; }
int bar(int) { return 0; }
};
int main()
{
std::cout << detect<foo, bar_t>{} << std::endl;
std::cout << detect<foo, bar_int_t>{} << std::endl;
std::cout << detect<foo, bar_string_t>{} << std::endl;
return 0;
}
上面的代码产生了预期的输出
1
1
0
您可以使用live demo。现在,我想测试一个类型 T 是否有一个具有特定签名的构造函数,例如T::T(U) 与另一种类型 U。是否可以使用检测成语来做到这一点?
【问题讨论】:
-
std::is_constructible有什么问题?