Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to directly call conversion operator?

Tags:

c++

struct Bob
{
    template<class T>
    void operator () () const
    {
        T t;
    }

    template<class T>
    operator T () const
    {
        T t;
        return t;
    }
};

I can directly call Bob's operator() like this

Bob b;
b.operator()<int>();

How to directly call the conversion operator with a specific template parameter like this?

Bob b;
std::string s = b.???<std::string>();

It's not possible to use static_cast

Bob b;
std::string s = static_cast<std::string>(b);

http://ideone.com/FoBKp7

error: call of overloaded ‘basic_string(Bob&)’ is ambiguous

Question How to call directly with template parameter OR it's not possible. I know there are workarounds using a wrapping function.

like image 734
Neil Kirk Avatar asked Aug 30 '13 18:08

Neil Kirk


2 Answers

You can call it directly (explicitly) like this:

Bob b;
std::string s = b.operator std::string();

but it's not "with a specific template parameter" (but there's no need for).

See also WhozCraig's comment

like image 184
gx_ Avatar answered Nov 20 '22 07:11

gx_


Use a helper function:

template< typename T >
T explicit_cast( T t ) { return t; }

int main()
{
    Bob b;
    std::string s = explicit_cast<std::string>(b);
}
like image 32
Daniel Frey Avatar answered Nov 20 '22 05:11

Daniel Frey