我正在尝试实现一个“解码器”,它可以根据预期的返回类型不同地对待输入数据。
下面的代码似乎适用于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) {
^
我真的不明白这意味着什么,为什么编译器不使用带有“模板模板”参数的定义?我有类似的“编码”数据的功能,它起作用了,我做错了什么?
我是想解决错误的问题吗?如何根据预期的返回类型“拆分”解码函数,同时保持其泛型(或者至少对向量类型和非向量类型有不同的处理方式)?谢谢。
发布于 2022-09-26 14:21:48
我相信问题在Foo
内部。您正在调用Bar<T>
,它显式地表示使用接受单个模板参数的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;
}
发布于 2022-09-26 12:47:45
在编写T
时,您试图在Foo()
中传递Foo()
(这是一种具体类型)。相反,您需要一个template<class, class> class V
,即带有两个类型参数的类模板。
https://stackoverflow.com/questions/73854336
复制相似问题