查看std::ref 和 std::cref,我認為它的作業方式是有兩個原型
template< class T >
std::reference_wrapper<const T> cref( const T& t ) noexcept;
template< class T >
void cref( const T&& ) = delete;
T&&模板功能被洗掉。
但是當我用一個類似的可變引數模板函式模仿它時,如果至少一個引數滿足條件,則編譯成功。所以現在我不明白這(不?)是如何或為什么起作用的。
template<typename ... Ts>
void foo(const Ts& ... ts) { }
template<typename ... Ts>
void foo(const Ts&& ...) = delete;
int main(){
std::string a{"sss"};
foo<std::string>(a);
//foo<std::string>("sss"); error, deleted foo
foo<std::string, std::string>(a, "sss"); // I was expecting error here
//foo<std::string, std::string>("aaaa", "sss"); error, deleted foo
foo<std::string, std::string, std::string>(a, "aaa", "sss"); // I was expecting error here
}
clang、gcc 和 msvc 似乎就是這種情況https://godbolt.org/z/8cboT48En
uj5u.com熱心網友回復:
普通字串文字是左值,因此您的測驗不是在測驗您想要的。使用作為右值的文字進行測驗,我發現您需要擁有 cv-ref 限定符的每個變體。
#include<iostream>
#include<utility>
#include<string>
template<typename ... Ts>
void foo(const Ts& ... ts) { }
template<typename ... Ts>
void foo(Ts& ... ts) { foo(std::as_const(ts)...); }
template<typename ... Ts>
void foo(const Ts&& ...) = delete;
template<typename ... Ts>
void foo(Ts&& ...) = delete;
using namespace std::string_literals;
int main(){
std::string a{"sss"};
foo(a);
// errors, as desired
// foo("sss"s);
// foo(a, "sss"s);
// foo("aaaa"s, "sss"s);
// foo(a, "aaa"s, "sss"s);
}
現場觀看
uj5u.com熱心網友回復:
為此,您可以檢查 std::is_lvalue_reference。
template<typename ... Ts, std::enable_if_t<(!std::is_lvalue_reference<Ts>::value && ...), int> = 0>
void foo(const Ts& ... ts) {}
然后所有像這樣的呼叫函式都是錯誤的。
foo<std::string>("sss"); //error, deleted foo
foo<std::string, std::string>(a, "sss"); // I was expecting error here
foo<std::string, std::string>("aaaa", "sss"); error, deleted foo
foo<std::string, std::string, std::string>(a, "aaa", "sss"); // I was expecting error here
uj5u.com熱心網友回復:
所以現在我不明白這(不?)是如何或為什么起作用的。
與參考包裝代碼相反,您的多載參考const:臨時檔案可以系結到。
如果您洗掉const,您會收到預期的錯誤:
template<typename ... Ts> void foo(Ts& ... ts) { /*..*/ }
template<typename ... Ts> void foo(const Ts&& ...) = delete;
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/527330.html
標籤:C 模板可变参数模板
上一篇:如何嵌套組合一堆函式?
下一篇:如何在C 17中實作概念
