指南C++功能模板类型
我有以下内容,它接受函数指针类型,并返回向量中每个参数的类型。
template <typename Ret, typename... Types>
auto ArgTypes(Ret(*pFn)(Types...))
{
std::vector<std::type_index> vec;
vec.insert(vec.end(), {typeid(Types)...});
return vec;
}
我这样调用它:
typedef int (*tExampleFn) (int a,bool b,char* c,long long d);
tExampleFn fakePtr = (tExampleFn)0;
auto argTypes = ArgTypes(&fakePtr);
如您所见,我必须将此假函数指针制作,以使模板工作。相反,我希望这样工作:
template <typename Ret, typename... Types> // guide Ret and Types into shape Ret(*pFn)(Types...) somehow
auto ArgTypes()
{
std::vector<std::type_index> vec;
vec.insert(vec.end(), {typeid(Types)...});
return vec;
}
typedef int (*tExampleFn) (int a,bool b,char* c,long long d);
auto argTypes = ArgTypes<tExampleFn>();
我无法让模板以这种方式工作。第一个模板arg ret被刺激了Typedef Texamplyfn的全部类型。我如何指导模板使用形状ret(*pfn)(类型...),但是 不得不传递中间功能指针。
I have the following, it accepts a function pointer type, and returns the typeid of each argument in a vector.
template <typename Ret, typename... Types>
auto ArgTypes(Ret(*pFn)(Types...))
{
std::vector<std::type_index> vec;
vec.insert(vec.end(), {typeid(Types)...});
return vec;
}
I invoke it like this:
typedef int (*tExampleFn) (int a,bool b,char* c,long long d);
tExampleFn fakePtr = (tExampleFn)0;
auto argTypes = ArgTypes(&fakePtr);
As you can see, I have to make this fake function pointer for the template to work. I would instead like it to work like this:
template <typename Ret, typename... Types> // guide Ret and Types into shape Ret(*pFn)(Types...) somehow
auto ArgTypes()
{
std::vector<std::type_index> vec;
vec.insert(vec.end(), {typeid(Types)...});
return vec;
}
typedef int (*tExampleFn) (int a,bool b,char* c,long long d);
auto argTypes = ArgTypes<tExampleFn>();
I cannot get the template to work this way. The first template arg Ret gets assinged the full type of the typedef tExampleFn. How can I guide the template to use the shape Ret(*pFn)(Types...), but without having to pass an intermediate function pointer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
谢谢大家,我将答案和评论与一些外部帮助结合在一起:
Thanks everyone, I've combined the answers and comments with some external help into the following:
如Nathanoliver所述,您可以通过
argtypes(texamplyfn {})
来调用第一个版本。为了避免完全创建功能指针类型的实例,您可以使用部分模板专业化。但是,这对功能模板不起作用。
As mentioned by NathanOliver you can call the first version via
ArgTypes(tExampleFn{})
.To avoid creating an instance of the function pointer type altogether you can use partial template specialization. This doesn't work for function templates though.