我開始使用模板,我想弄清楚為什么以下內容不能作業。
class testclass1
{
public:
template <typename...Ts>
using TFunc = std::function<void(Ts*...)>。
template <typename...Ts>
void SetFunction(TFunc<Ts...> tf)
{
//做一些事情。
}
};
template<typename...Ts>
class testclass2
{
public:
using TFunc = std::function<void(Ts*...)> 。
void SetFunction(TFunc tf)
{
//做一些事情。
}
};
void some_function(std::string*, double*)
{
}
int main()
{
testclass1 tc1;
testclass2<std::string, double> tc2;
testclass1::TFunc<std::string, double> tf1 = some_function;
tc1.SetFunction<std::string, double>(tf1)。
tc1.SetFunction<std::string, double>(testclass1::TFunc<std::string, double> {tf1}) 。
tc2.SetFunction(some_function)。
tc1.SetFunction<std::string, double>(some_function)。
}
除了最后一個版本,所有的作業都很正常
tc1.SetFunction<std::string, double> (some_function);
這實際上是我想做的,因為它有更少的模板,而且我不希望testclass1需要模板引數。
最后一行給出了下面的編譯錯誤:
沒有匹配的成員。
對'SetFunction'的呼叫沒有匹配的成員函式 我不明白額外的 "type-parameter-0-0 "是什么。直觀地說,這看起來很像鏈接到隱式*this指標的問題,但我不明白為什么TFunc會是一個成員函式,并且有一個隱式*this指標(或者這與std::function鏈接?另外,將代碼 通過瀏覽不同的相關Q&As,似乎你不能在模板函式中使用std::函式。這是這里的問題嗎? 有沒有辦法讓 提前感謝。 更新:我正在努力理解這個解釋,我想我有點明白了,但后來------想了想------我還是不能100%確定。考慮一下下面的代碼: 在這種情況下,只有 uj5u.com熱心網友回復: 似乎你不能使用 不,這個問題與 問題在于模板引數包的推導失敗。你指定了一些打包引數,但是編譯器怎么知道你是否指定了所有的引數?指定一些打包引數并讓編譯器推匯出其余的引數是可能的。所以編譯器還是會進行推理。 但是 (注意--在GCC 11 output中沒有提到"type-parameter-0-0",所以你的編譯器可能已經過時了)。 現在,為了解決這個問題,我們可以為 例如,使用一個身份識別的引數來進行替換。
例如,使用一個身份模板: (實時演示)
標籤: 上一篇:為cmd中的每一行變數運行命令
下一篇:C 中的變體的變體
template <typename...Ts> using TFunc = std::function<void(Ts*...)>;移到testclass1之外并沒有改變什么。
tc1.SetFunction<std::string, double>(some_function);在testclass1中發揮作用?template <typename...Ts>
using test_tuple = std::tuple<Ts...>。
template <typename...Ts>
void test_func(test_tuple<Ts...> tup)
{
//做一些事情。
//e.g., PrintTuple(tup);.
}
int main()
{
test_tuple<std::string, double> tt{"Hi", 3.1459f};
test_func<std::string>(tt)。
}
std::string在引數包中被指定,并且雙倍被推匯出來(所以不是所有的引數都在引數包中被指定)。但是為什么在這種情況下可以作業,而且我沒有得到一個錯誤呢?
std::function與模板函式std::function沒有關系。std::function<void(std::string*, double*)>不能從void(*)(std::string*, double*)推匯出來(而且在推導程序中不考慮隱式轉換)。因此出現了錯誤:
模板引數推導/替換失敗:
不匹配的型別 'std::function<void(Ts* ...)>' 和 'void (*)(std::string*, double*)'SetFunction的引數引入一個非教育性的背景關系。然后將從所提供的型別引數中進行替換。template<typename T>
struct type_identity {
using type = T。
};
class testclass1
{
public:
template <typename...Ts>
using TFunc = std::function<void(Ts*...)>。
template <typename...Ts>
void SetFunction(typename type_identity<TFunc<Ts...> > :type tf)
{
//做一些事情。
}
};
