防止对象被转换为任何类型C ++ [英] Prevent an object to be casted to any but one type C++

查看:119
本文介绍了防止对象被转换为任何类型C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了这个类:

template <class T>
class pure
{
public:
    pure(T const& attr) {
        this->attr = attr;
    }

    ~pure() {}

    T& operator=(T const& attr) {
        return attr;
    }

    operator T() {
        return this->attr;
    }

private:
    T attr;
};

这是一个存储类型 T 。当我想使用它的一个实例,我得到 attr (通过转换

This is a class that stores a value of type T. When I want to use an instance of it, I get the attr (by casting pure to T) instead of the instance (of pure) itself.

我的目标(< $<这里是一个类,不能被转换为除 attr 类型之外的任何类型,即 T

My goal here is to make a class that can't be casted to any type other than the type of attr, which is T.

推荐答案

如果你有一个C ++ 11能力的编译器,你可以添加eg以下成员函数:

If you have a C++11 capable compiler you could add e.g. the following member function:

template<typename U>
operator U() = delete;

该函数是一个通用转换操作符,并标记为已删除(这是C + +11)。因为它标记为已删除,则转换为 T 以外的任何其他类型都会导致编译器错误。

That function is a generic casting operator, and marked as deleted (which is a new feature in C++11). Because it's marked as deleted, then casting to any other type than T will lead to a compiler error.

如果你没有有一个C ++ 11编译器,那么你可以添加基本相同的函数声明为 private 函数,你会得到另一个错误:

If you don't have a C++11 capable compiler, then you can add basically the same function declaration as a private function, and you will get another error:

private:
    template<typename U>
    operator U();

这篇关于防止对象被转换为任何类型C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆