-2

I defined this class:

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;
};

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.

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055

1 Answers1

7

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

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

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.


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();
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • I have C++ 11 and your method worked very well, thanks a lot again ! I will mark your post as an answer ! Very good an simple, I like this delete keyword. – Marc-Antoine Jacob Apr 03 '15 at 12:22