Pergunta

Consider the double primitive type. Let we declare function as the following:

void foo(double);

Is it possible to describe a user-defined type which can be passed to foo as parameter?

Foi útil?

Solução

Of course, though not through actual inheritance but by simulating it with an implicit conversion:

#include <iostream>

struct MoreDouble
{
   operator double() { return 42.5; }
};

void foo(double x)
{
   std::cout << x << '\n';
}

int main()
{
   MoreDouble md;
   foo(md);
}

// Output: 42.5

(Live demo)

Whether this is a good idea is another question. I dislike implicit conversions in general so make sure you really need this before using it.

Outras dicas

Yes you can do so, if there is a user defines cast operator to your type.

void x(double){}

class A
{
    public:
    operator double(){return 0;}
};

int main()
{
    A a;
    x(a);
    return 0;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top