【发布时间】:2017-12-16 02:05:14
【问题描述】:
如何编译main() 的最后一行?
#include <initializer_list>
#include <type_traits>
#include <functional>
template <typename T>
struct foo {
foo(std::initializer_list<T>) { }
template <typename C> struct is_foo : std::false_type { };
template <typename U> struct is_foo<foo<U>> : std::true_type { };
template <typename Compare>
std::enable_if_t<!is_foo<Compare>::value> bar(foo&, Compare comp) {
bool b = comp(T(), T()); // This line compiles thanks to is_foo<Compare>.
}
void bar(foo&& f) { bar(std::forward<foo>(f), std::less<T>()); }
template <typename... Foos>
void bar(Foos&&...) { }
};
int main() {
foo<int> f = {1,2,3};
f.bar({4,5,6}); // Compiles fine
f.bar(f,f); // Compiles fine (thanks to is_foo<Compare>)
f.bar(f,{4,5,6}); // Won't compile
}
应该调用foo<T>::bar(Foos&&...)。
Test.cpp:27:17: error: no matching function for call to 'foo<int>::bar(foo<int>&, <brace-enclosed initializer list>)'
f.bar(f,{4,5,6}); // Won't compile
^
Test.cpp:13:44: note: candidate: template<class Compare> std::enable_if_t<(! foo<T>::is_foo<C>::value)> foo<T>::bar(foo<T>&, Compare) [with Compare = Compare; T = int]
std::enable_if_t<!is_foo<Compare>::value> bar(foo&, Compare comp) {
^~~
Test.cpp:13:44: note: template argument deduction/substitution failed:
Test.cpp:27:17: note: couldn't deduce template parameter 'Compare'
f.bar(f,{4,5,6});
【问题讨论】:
-
不幸的是,大括号初始化列表无法匹配转发引用。一个花括号初始化器列表“需要知道”它正在初始化什么。转发引用也需要知道它在转发什么。没人知道它到底应该是什么。
-
最简单的方法是使用简单的 foo
cast
标签: c++ c++11 variadic-templates overloading rvalue-reference