c++按类型大小而不是类型声明变量

标签 c++

有没有办法通过指定类型大小而不是大小本身来在 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?
}

或者,类中是否有一个可以返回模板类型名的访问器函数?

任何建议都会有所帮助。我知道还有其他方法可以解决此问题,但我特别想知道这两种情况是否都可行。 (我对第二种方法不太抱希望。)

我认为第一种方法可以通过使用 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

我的 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();
}

我只是觉得我无法用 auto 找出那种类型。但我宁愿错了!

最佳答案

在 C++11 中,你可以使用 auto让编译器推断出正确的类型,或者 decltype :

auto a = vec3.__vector[0];

还有 std::vector , 你有 value_type这是值类型,即 std::vector<float>::value_typefloat .

关于c++按类型大小而不是类型声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26614044/

相关文章:

c++ - C/C++ 中的常量

c++ - 多次使用相同的 C++ 访问说明符

c++ - C++ 中的多线程 SDL 错误

c++ - 确定导致段错误的代码行?

C++,读取和保存大量数字

java - 编译开源数据包捕获软件

c++ - 神秘的浮点异常

c++ - 指向数组

c++ - [[attributes]] 是 C++11 的新功能吗?