模板检查是否存在类成员函数? [英] Templated check for the existence of a class member function?
问题描述
是否可以编写一个模板来更改行为,具体取决于是否在类上定义了某个成员函数?
Is it possible to write a template that changes behavior depending on if a certain member function is defined on a class?
这是我想要的简单示例编写:
Here's a simple example of what I would want to write:
template<class T>
std::string optionalToString(T* obj)
{
if (FUNCTION_EXISTS(T->toString))
return obj->toString();
else
return "toString not defined";
}
因此,如果 Class T
定义了 toString()
,然后使用它;否则,事实并非如此。我不知道该怎么做的神奇部分是 FUNCTION_EXISTS部分。
So, if class T
has toString()
defined, then it uses it; otherwise, it doesn't. The magical part that I don't know how to do is the "FUNCTION_EXISTS" part.
推荐答案
是的,使用SFINAE,您可以检查给定的类是否提供某种方法。工作代码如下:
Yes, with SFINAE you can check if a given class does provide a certain method. Here's the working code:
#include <iostream>
struct Hello
{
int helloworld() { return 0; }
};
struct Generic {};
// SFINAE test
template <typename T>
class has_helloworld
{
typedef char one;
struct two { char x[2]; };
template <typename C> static one test( decltype(&C::helloworld) ) ;
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;
std::cout << has_helloworld<Generic>::value << std::endl;
return 0;
}
我刚刚在Linux和gcc 4.1 / 4.3上对其进行了测试。我不知道它是否可以移植到运行不同编译器的其他平台上。
I've just tested it with Linux and gcc 4.1/4.3. I don't know if it's portable to other platforms running different compilers.
这篇关于模板检查是否存在类成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!