【发布时间】:2019-03-14 21:39:52
【问题描述】:
这主要是关于固定大小数组相关的C++语法的一个角落的问题。
假设我有一个利用类型信息的函数,例如:
template<class T> void fun(T const& t){
std::cout << typeid(t).name() << std::endl;
}
我可以传递一个值或一个临时对象:
int i;
fun(i); // prints "int" ("i" actually)
fun(int{}); // prints "int" ("i" actually)
但是我不能对数组做同样的事情
double a[10][10];
fun(a); // ok, prints "a[10][10]" ("A10_A10_d" actually)
fun(double[10][10]); // doesn't compile
fun(double{}[10][10]); // doesn't compile
fun(double[10][10]{}); // doesn't compile
fun(double()[10][10]); // doesn't compile
fun(double[10][10]()); // doesn't compile
fun(double(&)[10][10]); // doesn't compile
fun(double(*)[10][10]); // doesn't compile
我原则上可以这样做:
typedef double a1010[10][10];
fun(a1010{});
但是,可以不预定义 typedef 吗?
是否有可能就地构造一个固定大小的数组作为函数参数?
完整代码:
template<class T> void fun(T const& t){
std::cout << typeid(t).name() << std::endl;
}
typedef double a1010[10][10];
int main(){
int i;
fun(i); // prints "int" ("i" actually)
double a[10][10];
fun(a); // prints "a[10][10]" ("A10_A10_d" actually)
fun(a1010{});
fun(int{}); // prints "int"
/* fun(double[10][10]); // doesn't compile
fun(double{}[10][10]); // doesn't compile
fun(double[10][10]{}); // doesn't compile
fun(double()[10][10]); // doesn't compile
fun(double[10][10]()); // doesn't compile
fun(double(&)[10][10]); // doesn't compile
fun(double(*)[10][10]); // doesn't compile
*/
return 0;
}
奖励积分(可能是赏金):可变大小的数组呢?
int N = 10;
f(double[N]);
【问题讨论】:
-
看看std::array,这可能就是你要找的。此外,你的意思是什么,真的吗?是为了类型检查,还是为了性能?如果您希望提高性能,那么您的尝试几乎肯定是错误的。
-
你考虑过Variable Template吗?
-
从好的方面来说,这不是大多数人想要做的事情。
-
@Frax,它纯粹是为了语法糖。通过单个参数传递类型(例如
double)和“数字”(10、10)。内容从未使用过,看起来静态数组曾经被分配或保留,因为在 clang 和 gcc 中,我能够在没有堆栈溢出的情况下提取double a [100000000][1000000000]; gun(a); gun((double[100000000][1000000000]){});。我也希望这些数字也可以是运行时的。 -
我建议将您的函数更改为
template<class T> struct Tag<T> {}; template<class T> void fun(tag<T>){ std::cout << typeid(T).name() << std::endl; }之类的东西,这样您就可以轻松传递类型(非默认可构造类型没有问题,您可以保留右值/左值常量信息,...)。用法类似于fun(tag<double[10][10]>{});或fun(tag<decltype(var)>{});
标签: c++ arrays c++11 rvalue temporary-objects