![](/img/trans.png)
[英]How to partially specialize function to invoke function with tuple elements as arguments
[英]How to specialize a function for a tuple parameter?
我有以下功能:
template <typename Functor, typename Arg>
decltype(auto) call(Functor f, Arg &&arg) { // (1)
// ..
}
我想為arg
是tuple
的情況創建一個特殊化。 我試過了:
template <typename Functor, typename... Args>
decltype(auto) call(Functor f, std::tuple<Args...> &&args) { // (2)
// ..
}
它可以單獨工作,但是當兩者同時存在時,即使參數為元組,(1)也會更好地匹配。 我正在使用clang 3.7編譯代碼。
如果您想避免編寫丑陋的SFINAE,則需要做一個間接的操作。 除了分配標簽外,您還可以委托給一個類模板,但是我更喜歡標簽
template<typename> class type { };
template <typename Functor, typename Arg>
decltype(auto) call(Functor f, Arg &&arg) {
return call(f, std::forward<Arg>(arg), type<std::decay_t<Arg>>());
}
template <typename Functor, typename Arg, typename T>
decltype(auto) call(Functor f, Arg &&arg, type<T>) {
...
}
template <typename Functor, typename Arg, typename ...T>
decltype(auto) call(Functor f, Arg &&arg, type<std::tuple<T...>>) {
...
}
我發現您的示例確實有效(並且vs2015同意)
基本情況是通用引用,它同時包含rvalue和rvalue(和引用)。 (現場演示http://ideone.com/kCBv3d )
decltype(auto) call(int &&arg) { // (1)
std::cout << "Base case" << std::endl;
}
decltype(auto) call(std::tuple<int> &&args) {
std::cout << "TTT" << std::endl;
}
/// main:
call(std::tuple<int>{1}); // TTT
call(2); // Base case
std::tuple<int> ti{5};
call(1,ti); // Base case (as expected!)
call(1,std::move(ti)); // TTT
請注意,您的重載使用r值引用(而不是轉發引用),因此其他任何內容(lvalue引用)都將使用基本情況。
據我了解,這都是超負荷的,但是有關的閱讀是Herb Sutter的這篇文章: http : //www.gotw.ca/publications/mill17.htm
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.