shinzou
shinzou

Reputation: 6192

Is there a way to add conversion operators to primitive types?

Is there a way to add conversion operators to primitive types?

For example:

Someclass x = (Someclass)7; //or even implicit casting

I know that it's possible to make a ctor in someclass that accepts an int, but is there a way to add a conversion operator to int instead?

Upvotes: 2

Views: 203

Answers (2)

kfsone
kfsone

Reputation: 24249

Your example code

SomeClass x = (SomeClass)7;

compiles if SomeClass has a constructor that accepts an int:

struct SomeClass {
    SomeClass(int) {}
};

int main() {
    SomeClass x = (SomeClass)7;
}

If you want to be able to convert a SomeClass into an integer, you want operator int()

#include <iostream>

class SomeClass {
    int m_n;

public:
    SomeClass(int n_) : m_n(n_) {}
    SomeClass() : m_n(0) {}

    operator int () { return m_n; }
};

int main() {
    SomeClass x = 7; // The cast is not required.
    std::cout << (int)x << "\n";
}

Live demo: http://ideone.com/fwija0

Without the constructor:

#include <iostream>

class SomeClass {
    int m_n;

public:
    SomeClass() : m_n(123) {}

    operator int () { return m_n; }
};

int main() {
    SomeClass x;
    std::cout << (int)x << "\n";
}

http://ideone.com/xfsdjp

If you are asking "how can I convert int to SomeClass with a conversion operator" the closest thing is operator=

#include <iostream>

class SomeClass {
public:
    int m_n;
    SomeClass() : m_n(0) {}
    SomeClass& operator = (int n) { m_n = n; return *this; }
};

int main() {
    SomeClass sc;
    std::cout << "sc.m_n = " << sc.m_n << "\n";
    sc = 5;
    std::cout << "sc.m_n = " << sc.m_n << "\n";
}

http://ideone.com/wDl4oP

Upvotes: 2

user2249683
user2249683

Reputation:

No, that is impossible. You can not change operations on primitive (builtin) types.

Upvotes: 2

Related Questions