[英]C++ detect any constructor with SFINAE
I tried to create a template class that should detect any constructor by using SFINAE and variadic templates. 我试图创建一个模板类,它应该通过使用SFINAE和可变参数模板来检测任何构造函数。 Here is code of the template:
这是模板的代码:
template <typename Type, typename ... Arguments>
struct IsConstructible
{
template <typename U, decltype(U(Arguments...))* = nullptr>
static char test();
template <typename U>
static long test(...);
static constexpr bool value = sizeof(test<Type>()) == sizeof(char);
};
However, when I test this with following type: 但是,当我用以下类型测试时:
struct MyBadType {
MyBadType(int x) { }
};
the result of this: 结果如下:
IsConstructible<MyBadType, int>::value;
is 0. Is there anything wrong with my template checker? 是0.我的模板检查器有什么问题吗? I am using MSVS 2015 express.
我正在使用MSVS 2015 express。
The code shouldn't compile; 代码不应该编译; if MSVC does so then it's using extensions.
如果MSVC这样做,那么它使用扩展。
template <typename U, decltype(U(Arguments...))* = nullptr>
That decltype
expression doesn't make sense. 这种
decltype
表达没有意义。 U(Arguments...)
is a function type, but you want to get the type of constructing a U
from Arguments...
. U(Arguments...)
是一个函数类型,但是你想从Arguments...
获得构造U
的类型Arguments...
You could use std::declval
for that: 您可以使用
std::declval
:
template <typename U, decltype(U(std::declval<Arguments>()...))* = nullptr>
There is a second issue: 还有第二个问题:
template <typename U, decltype(U(std::declval<Arguments>()...))* = nullptr>
static char test();
template <typename U>
static long test(...);
A call of test<type>()
would be ambiguous. test<type>()
调用将是不明确的。 The "classic" way to resolve the ambiguity is to give the preferred version a dummy parameter: 解决歧义的“经典”方法是为首选版本提供一个虚拟参数:
template <typename U, decltype(U(std::declval<Arguments>()...))* = nullptr>
static char test(int);
// here ^^^
template <typename U>
static long test(...);
Then you call the function like test<type>(0)
. 然后调用
test<type>(0)
的函数。
See this blog post for a more flexible way to resolve overload ambiguities. 请参阅此博客文章 ,了解更灵活的方法来解决过载歧义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.