有没有办法通过指定类型大小而不是大小本身来定义C++中的变量?或者有没有办法从函数返回一个类型?
template<typename T, int L>
class vector {
public:
T* __vector;
};
#ifdef USE_FLOAT
typedef vector<float, 3> vec3
#else
typedef vector<double, 3> vec3;
#endif
void myFunc(vec3) {
float a = vec3.__vector[0];
// AAHHH but what if vec3 is a vector of doubles?
// I can get the size of the type by
int s = sizeof(vec3[0]);
// So can I declare a variable by just giving the size of the variable?
}
Run Code Online (Sandbox Code Playgroud)
或者,无论如何在类中都有一个可以返回模板类型名称的访问器函数?
任何的意见都将会有帮助.我知道还有其他方法可以解决这个问题,但我特别想知道这两件事中是否有可能.(我对第二种方法的希望不大.)
我认为第一种方法是可以通过使用void指针和malloc'ing ...但我宁愿避免使用堆,只要坚持堆栈,如果可能的话.
编辑:
只是为了澄清,我不认为auto
在我的特殊情况下会有所帮助,尽管我没有解释原因.这是更完整的代码,并解释了为什么我不认为(肯定是错的)auto
不能解决问题.
我有另一个类似的类矩阵.
template<typename T, int L>
class matrix {
public:
T* __matrix;
};
#ifdef USE_FLOAT
typedef matrix<float, 4> mat4;
#else
typedef matrix<double, 4> mat4;
#endif
Run Code Online (Sandbox Code Playgroud)
我的myFunc函数看起来更像这样:
void myFunc(vec3) {
float a = vec3.__vector[0];
// AAHHH but what if vec3 is a vector of doubles?
// I can get the size of the type by
int s = sizeof(vec3[0]);
// So can I declare a variable by just giving the size of the variable?
matrix<sameTypeAsVec3, 4> mat();
}
Run Code Online (Sandbox Code Playgroud)
我只是觉得我不能弄清楚那种类型auto
.但我喜欢错!
在C++ 11中,您可以使用auto
让编译器推导出正确的类型,或者decltype
:
auto a = vec3.__vector[0];
Run Code Online (Sandbox Code Playgroud)
并用std::vector
,你value_type
这是值类型,即std::vector<float>::value_type
是float
.