【发布时间】:2016-08-04 21:17:56
【问题描述】:
有人能解释一下这里的奇怪输出吗?
#include <iostream>
#include <type_traits>
template <typename T>
constexpr auto has_foo_impl(int) -> decltype(typename T::foo{}, std::true_type{});
template <typename T>
constexpr auto has_foo_impl(long) -> std::false_type;
template <typename T>
constexpr bool has_foo() { return decltype(has_foo_impl<T>(0))::value; }
template <typename...> struct rank;
template <typename First, typename... Rest>
struct rank<First, Rest...> : rank<Rest...> {};
template <> struct rank<> {};
template <typename T, typename... Rest, typename... Args>
auto check (rank<T, Rest...>, Args... args) -> std::enable_if_t<has_foo<T>(), decltype(T(args...))> {
return T(args...);
}
//template <typename T, typename U, typename... Args>
//auto check (rank<T,U>, Args... args) -> std::enable_if_t<has_foo<T>(), decltype(T(args...))> {
// return T(args...);
//}
//
//template <typename T, typename... Args>
//auto check (rank<T>, Args... args) -> std::enable_if_t<has_foo<T>(), decltype(T(args...))> {
// return T(args...);
//}
template <typename... Args>
auto check (rank<>, Args...) { std::cout << "Nothing found.\n"; }
template <typename... Ts>
struct Factory {
template <typename... Args>
decltype(auto) create (Args... args) const {
return check(rank<Ts...>{}, args...);
}
};
struct Object {};
struct Thing {};
struct Blob {
using foo = int;
Blob (int, double) { print(); }
void print() const { std::cout << "Blob\n"; }
};
int main() {
Factory<Blob, Object, Thing>().create(4,3.5); // Blob
Factory<Object, Blob, Thing>().create(4,3.5); // Nothing found
Factory<Object, Thing, Blob>().create(4,3.5); // Nothing found
}
我希望看到Blob 输出三遍。当我取消注释已注释掉的重载check 时,我确实明白了。单个可变参数 check 函数不应该处理我注释掉的那些吗?毕竟,rank<First, Rest...> 派生自 rank<Rest...>。
我知道完成相同工作的其他方法,但我想知道为什么这种排名方法在这里不起作用。输出Nothing found表示通过了rank<>,也就是通过了中间等级。
【问题讨论】:
标签: c++ templates c++11 variadic-templates sfinae