【问题标题】:Visual C++ cares about the array size in function arguments. Is that correct?Visual C++ 关心函数参数中的数组大小。那是对的吗?
【发布时间】:2016-09-20 12:01:30
【问题描述】:

当我尝试编译由 CUDA 的 cudafe++ 工具生成的以下(损坏的)代码时,Visual Studio 会抛出错误 C2244。这是正确的行为吗? GCC 似乎并不关心签名不匹配。

代码:

template<int Size>
class MyClass {
public:
    MyClass(const int data[Size]);
};

template<int Size>
MyClass<Size> ::MyClass(const int data[]) {}

void func(MyClass<4> input) {}

输出:

test2.cpp(9) : error C2244: 'MyClass<Size>::MyClass' : unable to match function definition to an existing declaration
    test2.cpp(5) : see declaration of 'MyClass<Size>::MyClass'
    definition
    'MyClass<Size>::MyClass(const int [])'
    existing declarations
    'MyClass<Size>::MyClass(const int [Size])'

【问题讨论】:

  • 在参数中,const int data[Size]const int data[]const int *data 是等价的。也许 MSVC++ 有一个“一个声明规则”(作为the one definition rule 的变体,它表示“每个定义都由相同的标记序列组成”)。但是,声明不应该是这种情况,只有定义。
  • 在我看来就像 VC++ 中的一个错误。

标签: c++ arrays visual-c++ cuda


【解决方案1】:

我很确定这是不正确的。

int foo(const int []);
int foo(const int [4]);
int foo(const int *);

都应该声明相同的函数。话虽如此,您可能想要的是:

template<int Size>
class MyClass {
public:
    MyClass(const int (&data)[Size]);
};

template<int Size>
MyClass<Size> ::MyClass(const int (&data)[Size]) {}

这将接受正确大小的数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 2011-12-18
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    相关资源
    最近更新 更多