我正在玩 proposal of standard library support for the C++ detection idiom 。它是一个类似特征的元函数,用于确定类型 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
。是否可以使用检测惯用法来做到这一点?
最佳答案
修改检测
类以允许可变参数:
template <typename...>
using void_t = void;
template <typename AlwaysVoid, template <typename...> class Operation, typename... Args>
struct detect_impl : std::false_type { };
template <template <typename...> class Operation, typename... Args>
struct detect_impl<void_t<Operation<Args...>>, Operation, Args...> : std::true_type { };
添加硬编码 void 类型的别名:
template <template <typename...> class Operation, typename... Args>
using detect = detect_impl<void, Operation, Args...>;
// ~~~^
编写检测器:
template <typename T, typename... Us>
using has_constructor = decltype(T(std::declval<Us>()...));
测试你的类(class):
static_assert(detect<has_constructor, foo, foo>{}, "!");
关于c++ - 使用检测惯用法来确定类型是否具有带有特定签名的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35669304/