我正在尝试编写一个模板助手,让我检查一组类型是否与结构的成员类型匹配。到目前为止,我已经写了这个-
#include <iostream>
#include <functional>
struct foo {
int field1;
int field2;
};
template <typename...T, std::size_t ...indices >
constexpr bool construct (std::index_sequence<indices...>) {
foo s = {std::get<indices>(std::tuple<T...>())...};
return true;
}
template<typename...T>
static bool allowed(int) {
construct<T...>(std::index_sequence_for<T...>());
return true;
}
template<typename...T>
static bool allowed(long) {
return false;
}
int main() {
std::cout << allowed<int, int, int>(0);
return 0;
}
在这里,对allowed<int, int, int>
的调用显然是无效的,因为构造无法被调用(foo有2个成员,它正在用3初始化(。但还有另一个allow的实现,它以long
为自变量。既然是SFINAE,难道编译器不应该简单地匹配allowed的第二个模板实现并返回false
吗?但它反而给了我一个错误——
错误:'foo'的初始化程序太多
foo s = {std::get<indices>(std::tuple<T...>())...};
如果我只是注释掉allowed的第一个实现,一切都很好,我得到一个false。我对模板替换如何与隐式强制转换和函数重载交互感到困惑。如果不允许这样做,有没有办法达到同样的效果?
foo
不在即时上下文中,因此您会得到硬错误,而不是SFINAE。考虑一下:
#include <iostream>
#include <functional>
struct foo {
int field1;
int field2;
};
template <typename U, typename...T, std::size_t ...indices >
constexpr auto construct (std::index_sequence<indices...>) -> decltype(new U {std::get<indices>(std::tuple<T...>())...}) {
return nullptr;
}
template<typename...T, typename Q = decltype(construct<foo, T...>(std::index_sequence_for<T...>()))>
static bool allowed(int) {
return true;
}
template<typename...T>
static bool allowed(long) {
return false;
}
int main() {
std::cout << "allowed<int,int>(0) = " << allowed<int,int>(0) << std::endl;
std::cout << "allowed<int,int,int>(0) = " << allowed<int,int,int>(0) << std::endl;
return 0;
}