相关疑难解决方法(0)

是否可以编写模板来检查函数的存在?

是否可以编写一个模板来改变行为,具体取决于是否在类上定义了某个成员函数?

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

template<class T>
std::string optionalToString(T* obj)
{
    if (FUNCTION_EXISTS(T->toString))
        return obj->toString();
    else
        return "toString not defined";
}
Run Code Online (Sandbox Code Playgroud)

所以,如果class T已经toString()确定的话,就使用它; 否则,它没有.我不知道怎么做的神奇部分是"FUNCTION_EXISTS"部分.

c++ templates sfinae template-meta-programming

458
推荐指数
20
解决办法
14万
查看次数

SFINAE + sizeof =检测表达式是否编译

我刚刚发现了如何检查是否operator<<提供了类型.

template<class T> T& lvalue_of_type();
template<class T> T  rvalue_of_type();

template<class T>
struct is_printable
{
    template<class U> static char test(char(*)[sizeof(
        lvalue_of_type<std::ostream>() << rvalue_of_type<U>()
    )]);
    template<class U> static long test(...);

    enum { value = 1 == sizeof test<T>(0) };
    typedef boost::integral_constant<bool, value> type;
};
Run Code Online (Sandbox Code Playgroud)

这个技巧是众所周知的,还是我刚刚获得了诺贝尔奖的元编程?;)

编辑:我使代码更容易理解,更容易适应两个全局函数模板声明lvalue_of_typervalue_of_type.

c++ metaprogramming sfinae

12
推荐指数
1
解决办法
2170
查看次数