c++ - 如何确保一个类型的值只能被它的 friend 操纵?

标签 c++

我想创建一个类模板,ptrs_and_refs_only<T> ,只能通过指针和引用进行操作。换句话说,这种类型的值应该是不允许的,除了声明为 friend 的东西。 s 的类型。

具体来说,我希望编译器在遇到用作函数参数的这种类型时发出错误:

void foo(ptrs_and_refs_only<int> x);  // error!
void bar(ptrs_and_refs_only<int> &x); // ok
void baz(ptrs_and_refs_only<int> *x); // ok

我知道我可以做到 ptrs_and_refs_only<T>的复制构造函数 private ,但这似乎不会导致这段代码出错:

template<typename T>
  class ptrs_and_refs_only
{
  private:
    ptrs_and_refs_only() {}
    ptrs_and_refs_only(const ptrs_and_refs_only &) {}
};

void foo(ptrs_and_refs_only<int> x) {}

int main()
{
  return 0;
}

这种行为可能吗?

最佳答案

这是一个骨架,但我不知道它是否适合你的需要:

#include <type_traits>

template <typename T>
struct notype
{
private:
  typename std::enable_if<std::is_constructible<notype<T>, T const &>::value,
                          void>::type dummy();
  notype(T &) { }
};

void foo(notype<int>)   { } // Error
void foo(notype<int> &) { }
void foo(notype<int> *) { }

您仍然需要找到一种方法使该类对于某些客户端类来说是可构造的。

关于c++ - 如何确保一个类型的值只能被它的 friend 操纵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8829084/

相关文章:

c++ - 如何手动包装纹理坐标?

c++ - 无法打印斐波那契数列

C++/MFC : CDockablePane in CMDIChildWndEx

c++ - STL 容器速度与数组

c++ - 字符串转换的段错误?

c++ - 有效地找到最小值和最大值

c++ - 方法参数列表中的错误

c++ - 尝试使用 while 循环取消分配 vector ,任务管理器显示内存使用量正在增加

c++ - shared_ptr.reset() 不删除

C++字符串修改,不通过引用传递?