如何在C ++中将数组类型衰减为const指针类型?

时间:2014-07-16 15:10:19

标签: c++ arrays pointers

我想为给定的成员自动生成const访问器函数,但我在使用数组。有可能'衰变"数组类型为指针,但我不知道如何使类型的指向值const?添加const的任何明显方法都只应用指针。当然,我可以为数组类型制作专门的访问器,但它不是理想的解决方案。返回const指针指向const值也是可以接受的。这是不完整访问者的例子:

auto foo() const -> const typename std::decay<decltype(foo_)>::type { return foo_; }

1 个答案:

答案 0 :(得分:1)

如果您打算获取成员数组的地址,只需将其限定为const

#include <iostream>
using namespace std;

struct fooType {
};

class MyClass {
    public:

    fooType foo_[2];

    auto foo() const -> typename std::decay<const decltype(foo_)>::type
    { return &foo_[0]; }
};

int main() {
    MyClass classObj;
    classObj.foo();
    return 0;
}

http://ideone.com/PjclAf


编辑:

documentation表示

  

应用lvalue-to-rvalue,array-to-pointer和function-to-pointer   隐式转换为类型T,删除cv-qualifiers ,并定义   结果类型为成员typedef类型。 这是类型   转换为值时应用于所有函数参数。

(强调我的)

这里的重要内容是std::decay()总是采取行动来模拟&#34;一种按值传递的机制,你需要它的类型。如果可以在按值传递调用中删除Cv限定符,则如果它们实际定义了结果类型则不会被删除。

采用以下示例:

#include <iostream>
#include <type_traits>

template <typename T, typename U>
struct decay_equiv : 
    std::is_same<typename std::decay<T>::type, U>::type 
{};

void function1(int happyX) {
    // happyX can be modified, it's just a local variable
    happyX = 42;
    std::cout << happyX << std::endl;
}

void function2(const int *ptrByValue) {
    // ptrByValue can be modified, however its type is 'const int' and that CANNOT be modified
    ptrByValue = (const int*)0xDEADBEEF;
    std::cout << ptrByValue << std::endl;
}

int main()
{
    std::cout << std::boolalpha
              << decay_equiv<const int, int>::value << std::endl      // cv-qualifiers are dropped (pass-by-value)
              << decay_equiv<const int[2], int*>::value << std::endl; // cv-qualifiers here CANNOT be dropped, they're part of the type even if passed by value

    const int myConstValue = 55;
    function1(myConstValue);

    const int myArrayToConstValues[2] = {4,2};
    function2(myArrayToConstValues);

    return 0;
}

http://ideone.com/AW6TJS

在你的例子中,你要求一个常量的返回值(你不能修改第一个元素的地址),但是在尾随的返回类型中要求一个非常量的返回值,即&#39;为什么编译器抱怨和我刚才写的是为什么const不能被std::decay()删除的原因:即使是在按值传递的情况下它也是类型的一部分(例如{{ 1}})。