use*_*257 12 c++ types function c++11
有功能定义:
void f(int) { }
Run Code Online (Sandbox Code Playgroud)
我想定义:
int a;
Run Code Online (Sandbox Code Playgroud)
但如果函数定义更改为:
void f(double) { }
Run Code Online (Sandbox Code Playgroud)
变量定义必须变为:
double a;
Run Code Online (Sandbox Code Playgroud)
也就是说,"a"的类型必须与"f"函数的第一个参数相同.我需要以下内容:
decltype_of_argument<f, 0> a;
Run Code Online (Sandbox Code Playgroud)
在C++中有可能吗?
Arn*_*rtz 21
您可以通过模板元编程获取类型:
template <class F> struct ArgType;
template <class R, class T>
struct ArgType<R(*)(T)> {
typedef T type;
};
void f(int) {}
#include <type_traits>
#include <iostream>
int main() {
// To prove
std::cout << std::is_same< ArgType<decltype(&f)>::type, int >::value << '\n';
// To use
ArgType<decltype(&f)>::type a;
}
Run Code Online (Sandbox Code Playgroud)
根据您想要使用它的位置,您需要将此litte模板专门用于其他可调用实体,例如成员函数poitners,具有更多参数的函数,仿函数等.在Boost库中有更多复杂的方法,例如https:/ /stackoverflow.com/a/15645459/1838266
警告:只有当函数/ callable的名称明确映射到一个函数签名时,所有这些实用程序才有效.如果一个函数被重载或者仿函数有不止一个operator(),右边的功能/操作员必须通过明确铸造正确的签名,这使得通过模板好看不中用找出签名的一部分被拾起.这也以某种方式应用于模板,虽然获得明确特殊化的可调用的签名可能仍然有用,例如:
template <unsigned N, class F> struct ArgType; //somewhat more sophisitcated
template <class T> void f(int, T);
ArgType<0, decltype(&f<double>)> //int - ArgType has it's use here
ArgType<1, decltype(&f<double>)> //double - here it's useless...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3101 次 |
| 最近记录: |