我想创建一个类模板,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/