C ++解析函数类型模板参数 [英] C++ parsing function-type template argument
问题描述
我想要使用函数类型(包括参数和返回类型)的模板参数调用函数,即 double(int,long)
,并在函数中分隔类型并单独使用它们。
例如,我想能够调用函数
printRes< double(int,long)>();
此函数应该解析模板参数并提取返回类型 double
并输出。
我知道如何使用类和可变参数模板:
#include< iostream>
#include< typeinfo>
template< typename T>
class A {};
template< typename Res,typename ... Args>
class A< Res(Args ...)> {//解析模板参数
public:
void printRes(){
std :: cout< typeid(Res).name()<< std :: endl;
}
};
然后我可以这样使用:
int main(){
A< double(int,long)>一个;
a.printRes();
}
哪些输出:
d
我想使用一个简单的函数代替。这是我想出的:
模板< typename Res,typename ... Args>
void printRes(){
std :: cout<< typeid(Res).name()<< std :: endl;但是,现在我必须像下面这样指定模板参数:
int main(){
printRes< double,int,long>();
}
是否有任何方法来实现该函数,模板参数作为类版本(即 double(int,long)
)?
解决方案 我想你几乎在那里。你可以在函数模板中使用你的trait。下面是一个可能的实现:
#include< iostream>
#include< typeinfo>
template< typename T>
struct A {};
template< typename Res,typename ... Args>
struct A< Res(Args ...)>
{
using type = Res;
};
template< typename T>
void printRes()
{
使用Res = typename A< T> :: type;
std :: cout<< typeid(Res).name()<< std :: endl;
}
int main()
{
printRes< double(int,long)>();
}
这是一个实例。
I want to be able to call a function with a template parameter that is of function type (including parameter and return types), i.e. double(int, long)
, and in the function separate the types and use them individually.
For example I want to be able to call a function
printRes<double(int, long)>();
This function above should parse the template argument and extract the return type double
and output it.
I know how to do this using a class and variadic templates:
#include <iostream>
#include <typeinfo>
template <typename T>
class A {};
template <typename Res, typename... Args>
class A<Res (Args...)> { // Parse template argument
public:
void printRes() {
std::cout << typeid(Res).name() << std::endl;
}
};
Then I can use it like this:
int main() {
A<double(int, long)> a;
a.printRes();
}
Which outputs:
d
I want to do this using a simple function instead. This is what I came up with:
template <typename Res, typename... Args>
void printRes() {
std::cout << typeid(Res).name() << std::endl;
}
However, now I must specify the template parameters like this instead:
int main() {
printRes<double, int, long>();
}
Is there any way to implement the function so it can be called using the same template parameter as the class-version (i.e. double(int, long)
)?
解决方案 I guess you are almost there. You can use your trait inside a function template. Here is a possible implementation:
#include <iostream>
#include <typeinfo>
template <typename T>
struct A { };
template<typename Res, typename... Args>
struct A<Res (Args...)>
{
using type = Res;
};
template<typename T>
void printRes()
{
using Res = typename A<T>::type;
std::cout << typeid(Res).name() << std::endl;
}
int main()
{
printRes<double(int, long)>();
}
And here is a live example.
这篇关于C ++解析函数类型模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文