기본적으로, 벡터 (유형) 매개 변수와 비 벡터 유형 매개 변수에 대해 함수가 다르게 동작하도록하려고합니다.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>();
}
벡터를 typename으로 사용하면서 벡터를 반환하려면 int를 typename으로 사용하면서 int를 반환하십시오.
그러나 is_vector (int) :: value가 false를 반환하므로 내 컴파일러에서 "left of '.front'에 class/struct/union이 있어야한다고보고하는 이유는 무엇입니까?
내가 원하는 것은 문자열을 벡터 (형식) 또는 벡터 (벡터 (형식))로 올바르게 deserialize하는 것입니다.
multidemonsional 벡터를 템플릿 매개 변수로 전달하면서 재귀 적으로 read 함수를 호출해야하지만 컴파일러에서이를 수행하지 않아도됩니다.
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 메타 프로그래밍에 대해 잘 모릅니다. 어떻게 벡터와 팟 유형에 대해 다른 코드를 생성 할 수 있습니까? – iouvxz