c++ - 模板化检查是否存在类成员函数?

标签 c++ templates template-meta-programming sfinae

是否可以编写一个模板,根据类中是否定义了某个成员函数来更改行为?

这是我想写的一个简单例子:

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”部分。

最佳答案

是的,使用 SFINAE,您可以检查给定的类是否提供了特定的方法。这是工作代码:

#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 对其进行了测试。我不知道它是否可以移植到运行不同编译器的其他平台。

关于c++ - 模板化检查是否存在类成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23989825/

相关文章:

c++ - 使用流将对象转换为字符串

c++ - 为什么在发送几 block 数据后文件上传停止(使用 multipart/form-data)?

c++ - 未使用 NULL 宏指定空指针常量

C# 泛型方法值

c++ - 在模板实例化期间,文字值不被视为常量表达式

c++ - 常量的编译时检查

c++ - 析构函数 con C++ with g++(中止(核心转储))

javascript - 如何在 Ghost 中找到所有带有特定标签的帖子并遍历它们?

C++ 模板编译错误 - 递归类型或函数依赖

c++ - 编写一个通用内核并将其映射到不同的 ISA