Q
Qi
class SomeData
{
public:
template <typename T>
operator T () const {
// convert the object to T and return as T
}
};
I have a class to hold any data type (int, string, etc),
something like Windows COM VARIANT, to convert the object to real
data, I have two choices,
Choice 1, as above, write a type cast operator to convert
to any type.
Pros: simply use. The user may not notice the difference between
SomeData and other data type.
Cons: This is my question. Is it dangerous? I'm scared to see
an object can be implicitly converted to other data type.
I also guess it's quite error prone and hard to debug, am I right?
Is it common in C++ practice to make that kind of type cast
operator?
Choice 2, use a global template function to do that,
template <typename T>
T convert(const SomeData & data);
Pros: no implicitly type conversion.
Cons: tedious to call that function every where.
However, the syntax calling that function is quite like the built-in
cast operators, such like static_cast.
Final question, which choice is better you think?
{
public:
template <typename T>
operator T () const {
// convert the object to T and return as T
}
};
I have a class to hold any data type (int, string, etc),
something like Windows COM VARIANT, to convert the object to real
data, I have two choices,
Choice 1, as above, write a type cast operator to convert
to any type.
Pros: simply use. The user may not notice the difference between
SomeData and other data type.
Cons: This is my question. Is it dangerous? I'm scared to see
an object can be implicitly converted to other data type.
I also guess it's quite error prone and hard to debug, am I right?
Is it common in C++ practice to make that kind of type cast
operator?
Choice 2, use a global template function to do that,
template <typename T>
T convert(const SomeData & data);
Pros: no implicitly type conversion.
Cons: tedious to call that function every where.
However, the syntax calling that function is quite like the built-in
cast operators, such like static_cast.
Final question, which choice is better you think?