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

eat*_*hil 1 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?
}
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.但我喜欢错!

Jar*_*d42 6

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

auto a = vec3.__vector[0];
Run Code Online (Sandbox Code Playgroud)

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

  • @phileaton:你可以把类型设为`decltype(vec3 .__ vector [0])`,如果你在不能使用`auto`的环境中需要它.(假设你当然不是过去的生活;在这种情况下,定义一个嵌套的`typedef`作为另一个答案描述). (3认同)
  • 仅限C++ 11或更高版本. (2认同)
  • 你是对的,没有明显的限制,但是如果没有注意到C++ 11的要求,他可能无法正确配置他的编译器以支持C++ 11并最终导致编译错误. (2认同)