![](/img/trans.png)
[英]How can I use SFINAE to disable a function inside a class based on template type
[英]How can I use SFINAE to create a template function for containers, and deduce the return type based on an operator?
我嘗試制作一個'generateCombinations'函數,該函數將容納兩個容器的項,並生成它們的組合的容器(例如{“ hello”},{“ world”,“ friend”}會產生{“ hello world”, “ hello friend”}。我試圖使用SFINAE和operator +()上的decltype來推斷返回類型,但是我遇到了很多錯誤,嘗試了許多不同的方法,這是當前版本:
#include <vector>
template<typename T, typename S>
using CombinationResult = decltype(operator+(T(),S()));
template<typename T, typename S>
using CombinationResultContainer = std::vector< CombinationResult<T, S>>;
template<typename T, typename S>
CombinationResultContainer<typename T::value_type,typename S::value_type> generateCombinations(T&& first, S&& second)
{
CombinationResultContainer<typename T::value_type, typename S::value_type> result;
result.reserve(first.size() * second.size());
for (auto& t : first)
for (auto& s : second)
result.push_back(t + s);
return result;
}
void main()
{
std::vector<std::string>v1;
std::vector<std::string>v2;
generateCombinations(v1,v2);
}
目前,我得到以下錯誤:C2672'generateCombinations':找不到匹配的重載函數
C2893無法專用於功能模板'std :: vector> generateCombinations(T &&,S &&)'
T
和U
不是您的想法。 您可能希望它們都為std::vector<std::string>
,但是由於v1
和v2
是左值,因此這意味着T
和U
都是std::vector<std::string>&
因為參考崩潰 。 當您嘗試執行以下操作時:
CombinationResultContainer<typename T::value_type, typename S::value_type>
這將不起作用,因為T
和U
不是類類型,而是引用。 這是沿着邊模板自變量推導 轉發引用的本質。
由於函數中沒有任何內容依賴於T
或U
是否為左值引用這一事實,因此建議您使用左值引用代替const( T const&
和U const&
)。 這將推斷出T
和U
為預期的類型。
您在尋找笛卡爾積嗎? 嘗試范圍v3
view::cartesian_product
您的代碼的問題是,您需要刪除T和S的引用。
typename std::decay_t<T>::value_type
與S相同
要么
typename boost::range_value<T>::type
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.