基本上,我想打一個函數的行爲不同的向量(類型)參數和非矢量類型參數。C++如何使用向量專門化模板<T>?
#include <vector>
using namespace std;
template <typename type>
struct is_vector {
static const bool value = false;
};
template <typename type>
struct is_vector<vector<type>>
{
static const bool value = true;
};
template <typename type>
type read()
{
if (is_vector<type>::value)
{
type vec(10);
vec.front()=1;//left of '.front' must have class/struct/union
return vec;
}
else
{
return{};
}
}
int main()
{
auto i= read<int>();
}
我想在矢量使用的類型名稱返回一個載體,同時使用INT作爲類型名返回一個int。
但由於is_vector(INT)::,爲什麼我的編譯器報告「左‘.front’必須有類/結構/聯合」?我怎樣才能使它工作值返回false?
我想達到什麼是正確反序列化一個字符串向量(類型)或向量(矢量(種))。
我需要遞歸調用的讀取功能,同時傳遞一個multidemonsional載體作爲模板參數,但是編譯器不允許我這樣做。
template <typename type>
struct is_vector {
static const bool value = false;
};
template <typename type>
struct is_vector<vector<type>>
{
static const bool value = true;
};
template <typename type>
type read(char*& str)
{
if (is_vector<type>::value)
{
type vec(read<uint8_t>(str));
for (auto& e : vec)
e = read<type::value_type>(str);
return vec;
}
return *reinterpret_cast<type*>((str += sizeof(type)) - sizeof(type));
}
所以我嘗試了專業化。
template<>
vector<int> read<vector<int>>(char*& str)
{
vector<int> vec(read<uint8_t>(str));
for (auto& e : vec)
e = read<int>(str);
return vec;
}//works
template <typename type>
template <>
vector<type> read<vector<type>>(char*& str)
{
vector<type> vec(read<uint8_t>(str));
for (auto& e : vec)
e = read<type>(str);
return vec;
}//don't work
我真的需要手動重寫我讀功能爲每一種類型的怎麼用?
(如向量(矢量(向量(INT)))?)
你用於向量檢查是*遊程時間*檢查。該分支中的所有代碼仍然需要編譯。 –
首先:'is_vector'謂詞在編譯時被評估。在if中使用它表示您沒有完全明白應該使用哪些模板。 – Albjenow
@Albjenow我不太瞭解元編程,我怎樣才能讓我的函數爲矢量和pod類型生成不同的代碼? – iouvxz