相关疑难解决方法(0)

const对象传染媒介给编译错误

我在我的代码中声明了以下内容

vector <const A> mylist; 
Run Code Online (Sandbox Code Playgroud)

我得到以下编译错误 -

new_allocator.h:75: error: `const _Tp* __gnu_cxx::new_allocator<_Tp>::address(const _Tp&) const \[with _Tp = const A]' and `_Tp* __gnu_cxx::new_allocator<_Tp>::address(_Tp&) const [with _Tp = const A]' cannot be overloaded
Run Code Online (Sandbox Code Playgroud)

但如果宣布 -

vector <A> mylist;
Run Code Online (Sandbox Code Playgroud)

我的代码编译.

在这种情况下不允许使用const吗?

我在这里复制我的代码供大家参考 -

#include <iostream>
#include <vector>

using namespace std;
class A
{
public:
    A () {cout << "default constructor\n";}
    A (int i): m(i) {cout << "non-default constructor\n";}

private:
    int m;
};

int main (void)
{
    vector<const A> mylist;

    mylist.push_back(1);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ stdvector c++98

35
推荐指数
2
解决办法
1万
查看次数

是否允许在const定义的对象上抛弃const,只要它实际上没有被修改?

是否允许以下​​内容:

const int const_array[] = { 42 };

int maybe_inc(bool write, int* array) {
  if (write) array[0]++;
  return array[0];
}

int main() {
  return maybe_inc(false, const_cast<int *>(const_array));
}
Run Code Online (Sandbox Code Playgroud)

特别地,它是确定以铸远的常量性const_array,将其定义为const,只要对象是不实际修改,如在实施例?

c++ const const-cast undefined-behavior

12
推荐指数
1
解决办法
349
查看次数

基于布尔模板参数启用方法

我想基于布尔模板参数实现一个私有函数.像这样的东西:

#include <iostream>

using namespace std;

template <bool is_enabled = true>
class Aggregator {
public:
    void fun(int a) {
        funInternal(a);
    }

private:
    void funInternal(int a, typename std::enable_if<is_enabled>::type* = 0) {
        std::cout << "Feature is enabled!" << std::endl;
    }

    void funInternal(int a, typename std::enable_if<!is_enabled>::type* = 0) {
        std::cout << "Feature is disabled!" << std::endl;
    }
};

int main()
{
   Aggregator<true> a1;
   Aggregator<false> a2;

   a1.fun(5);
   a2.fun(5);

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是上面的程序没有编译:错误:'struct std :: enable_if'中没有名为'type'的类型void funInternal(int a,typename std :: enable_if :: type*= 0).

是否有可能通过enable_if实现所需的行为?

c++ templates enable-if

7
推荐指数
1
解决办法
4374
查看次数