3

As part of a method to check the existence of specific free functions, I have a type that is designed to be implicitly convertible to any other type:

struct AnyConvert
{
  template <class Dest>
  operator Dest & ();

  template <class Dest>
  operator Dest const & () const;
};

I use AnyConvert as a catchall in function parameters I'm not picky about when checking if the function exists. Note that this type is only ever used for metaprogramming at compile time.

This works well except for the following scenario:

template <class T> struct SomeType {};

template <class T>
int someFunction( SomeType<T> );

int someOtherFunction( SomeType<int> );

decltype( someOtherFunction( AnyConvert() ); // works
decltype( someFunction( AnyConvert() ); // does not work

I don't have any advance knowledge to the type AnyConvert is supposed to convert to. I also cannot modify the type that it should implicitly convert to. I tried adding functions like:

template <template <typename> class Dest, class ... T>
operator Dest<T...> & ();

to AnyConvert, but this doesn't seem to solve the problem either. The compiler error generated tends to look something like:

‘AnyConvert’ is not derived from ‘SomeType<T>’

So my question is: How can I create a type that will implicitly convert to templated types when the template type is not specified? It might turn out that this isn't possible, in which case I'll need to come up with a better way to check that a subset of function parameters are correct.

Community
  • 1
  • 1
Azoth
  • 1,652
  • 16
  • 24
  • Seems like you might be able to utilize some of the methods that are used by Boost's Type Traits library, if not just use the library itself. In particular, the function_traits functor seems like it would either be useful, or else have useful techniques you could leverage. http://www.boost.org/doc/libs/1_56_0/libs/type_traits/doc/html/index.html – jwismar Oct 23 '14 at 00:27
  • Found another answer where someone has created a traits class to answer this specific question, as to whether a given function exists or not. http://stackoverflow.com/a/9154394/279130 – jwismar Oct 23 '14 at 00:32
  • @Azoth Template argument deduction happens with the exact, sans cv, type. Conversion sequences, user-defined or otherwise, don't come into play at this stage. They are considered during overload resolution, by which point the template function would have been discarded as a candidate. – Pradhan Oct 23 '14 at 05:19
  • @jwismar: That method unfortunately does not allow one to enforce specific const requirements over the parameters. As detailed in my linked question, I need to make sure a function exists with specific const requirements. `T &` template parameters will happily instantiate for a `T const &` as well as a non-const `T`, so they are indistinguishable using the method in that post. @Pradhan I had a feeling this was the case - I'll have to try and come up with a better solution. – Azoth Oct 23 '14 at 21:11

0 Answers0