I want to make the C++ template do something different depending on the presence or absence of the function.
Is there a function that acts as FUNCTION_EXISTS()
in the code I made?
template<class T>
std::string optionalToString(T* obj)
{
if (FUNCTION_EXISTS(T->toString))
return obj->toString();
else
return "toString not defined";
}
#include <iostream>
struct Hello
{
int helloworld()
{ { return 0; }
};
struct Generic {};
// // SFINAE test
template <typename T>
class has_helloworld
{
typedef char one;
typedef long two;
template <typename C> static one& test (type of (&C::helloworld); //check the helloworld method
template <typename C> static two& test(...);
public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
};
int main(int argc, char *argv[])
{
std::cout << has_helloworld<Hello>::value << std::endl; // result : 1
std::cout << has_helloworld<Generic>::value << std::endl; // result : 0
return 0;
}
© 2024 OneMinuteCode. All rights reserved.