我正在嘗試實作一個“解碼器”,它可以根據預期的回傳型別對輸入資料進行不同的處理。
以下代碼似乎在https://cppinsights.io/中作業:
#include <cstring>
#include <vector>
template<template <class, class> class V, typename T>
void Bar(V<T, std::allocator<T>> &v, char** c) {
size_t s = *(size_t*)*c;
v.resize(s);
memcpy((char*)&v[0], *c, s * sizeof(T));
}
template<typename T>
inline void Bar(T &t, char** c) {
t = *(T*)*c;
}
template<typename T>
T Foo(char** c) {
T t;
Bar<T>(t, c);
return t;
}
char bob[] = {8,0,0,0,0,0,0,0,5,0,0,0,6,0,0,0,7,0,0,0,9,0,0,0,1,0,0,0,2,0,0,0,3,0,0,0,4,0,0,0};
char boz[] = {5,0,0,0};
int baz = Foo<int>((char **)&boz);
std::vector<int> bub = Foo<std::vector<int>>((char **)&bob);
所以我認為最終呼叫Foo將使用的第一個定義,Bar但這并沒有發生,如果我洗掉 的第二個定義Bar,以下代碼將無法編譯:
#include <cstring>
#include <vector>
template<template <class, class> class V, typename T>
void Bar(V<T, std::allocator<T>> &v, char** c) {
size_t s = *(size_t*)*c;
v.resize(s);
memcpy((char*)&v[0], *c, s * sizeof(T));
}
template<typename T>
T Foo(char** c) {
T t;
Bar<T>(t, c);
return t;
}
char bob[] = {8,0,0,0,0,0,0,0,5,0,0,0,6,0,0,0,7,0,0,0,9,0,0,0,1,0,0,0,2,0,0,0,3,0,0,0,4,0,0,0};
std::vector<int> bub = Foo<std::vector<int>>((char **)&bob);
我收到以下錯誤訊息:
error: no matching function for call to 'Bar'
template<typename T> T Foo(char** c) { T t; Bar<T>(t, c); return t; }
^~~~~~
note: in instantiation of function template specialization 'Foo<std::vector<int>>' requested here
std::vector<int> bub = Foo<std::vector<int>>((char **)&bob);
^
note: candidate template ignored: invalid explicitly-specified argument for template parameter 'V'
template<template <class, class> class V, typename T> void Bar(V<T, std::allocator<T>> &v, char** c) {
^
我真的不明白這是什么意思,為什么編譯器不使用帶有“模板模板”引數的定義?我有類似的“編碼”資料的功能,它可以作業,我做錯了什么?
我試圖解決錯誤的問題嗎?如何根據預期的回傳型別“拆分”解碼函式,同時保持其通用性(或者至少對向量與非向量型別進行不同的處理)?謝謝。
uj5u.com熱心網友回復:
當您撰寫T. 相反,您需要一個那里,即一個具有兩個型別引數的類模板。Foo()Bar<T>(...)template<class, class> class V
uj5u.com熱心網友回復:
我相信問題在里面Foo。您正在呼叫Bar<T>which 明確表示使用Bar帶有單個模板引數的使用。IE,您確保template template永遠不會選擇專業化。相反,讓它自動推斷。
這對我有用:https ://godbolt.org/z/14h1fdTMT
template<typename T>
T Foo(char** c) {
T t;
Bar(t, c); // auto-deduce here
return t;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/513362.html
標籤:C c 11模板
