0

I have defined many objects, and for some of them, i defined a function :

template <typename Ratio> 
auto print(const T &t, bool a= true, bool b= true)
{
    std::stringstream ss;
    // ... do stuff ...
    return ss.str();
}

where T is the type of one of the objects for which print is defined. Ratio is used inside the function.

My question is : Is there a way for a type T to find if this function exists ?

For others uses, i already used templates and SFINAE to detect if a class member method exists. But for my problem here, i can't find the solution ... Anyone ?

Thanks, Ben

PS : Example of SFINAE use in my code, where i needed to detect if a class member method exists .

static T none() { ... }

/**
 * SFINAE for checking id none method exists
 */
template <class T>
static auto hasNoneMethod(int)
    -> std::integral_constant<bool, std::is_same<T, decltype(T::none())>::value>;
template <class>
static auto hasNoneMethod(...) -> std::false_type;

/**
 * Type-Function
 */
template <typename T>
struct HasNoneMethod: decltype(detail::hasNoneMethod<T>(0)) {
};
Ben L.
  • 23
  • 1
  • 5
  • 1
    template you mean T? – Humam Helfawi Aug 02 '16 at 10:01
  • You have a `typename Ratio` but use `T`... Are they the same parameter? Have you tried anything? – Holt Aug 02 '16 at 10:01
  • What do you mean does it exist? As it stands (provided you correct your template parameter name typo) it will be automatically generated for any type that you want to use it with as it has no SFINAE constraints. – Smeeheey Aug 02 '16 at 10:03
  • What solution did you use for methods? – rocambille Aug 02 '16 at 10:04
  • T is the type of one of the objects for which print is defined. Ratio is used inside the function. – Ben L. Aug 02 '16 at 10:06
  • Possible duplicate(s): [Type trait: Check if class have specific function (maybe inherit)](http://stackoverflow.com/q/36692345/514235) ......AND...... [How to check if a member name (variable or function) exists in a class, with or without specifying type?](http://stackoverflow.com/q/36079170/514235). Also I am putting a close vote for "Unclear what you are asking". – iammilind Aug 02 '16 at 10:12

1 Answers1

1

You may use something like this:

template <class T>
static auto hasPrintMethod(int)
->std::integral_constant<bool, std::is_class<decltype(print(T()))>::value>;

template <class>
static auto hasPrintMethod(...)->std::false_type;

template <typename T>
struct HasPrintMethod : decltype(hasPrintMethod<T>(0)) {
};

Here the decltype(print(T())) is std::string for classes for which your non-member function is defined, and an erroneous type for other classes. So, according to SFINAE concept, HasPrintMethod<A>::value is equal to true for class A with print function defined and is equal to false otherwise.

alexeykuzmin0
  • 6,344
  • 2
  • 28
  • 51