我已经阅读了有关此问题的各种权威资料,包括Dewhurst但对于这个看似简单的问题却没有取得任何进展。
我想做的是call a C++ 函数对象,(基本上,任何你可以调用的东西,一个纯函数或一个带()的类),并返回它的值,如果它不是 void ,否则返回“true”。
using std:
struct Foo {
void operator()() { cout << "Foo/"l; }
};
struct Bar {
bool operator()() { cout << "Bar/"; return true; }
};
Foo foo;
Bar bar;
bool baz() { cout << "baz/"; return true; }
void bang() { cout << "bang/"; }
const char* print(bool b) { cout << b ? "true/" : "false/"; }
template <typename Functor> bool magicCallFunction(Functor f) {
return true; // Lots of template magic occurs here
// that results in the functor being called.
}
int main(int argc, char** argv) {
print(magicCallFunction(foo));
print(magicCallFunction(bar));
print(magicCallFunction(baz));
print(magicCallFunction(bang));
printf("\n");
}
// Results: Foo/true/Bar/true/baz/true/bang/true
UPDATE
感谢您的想法和想法!
基于此,我实际上决定将所有模板提升一级 - 所以我有:
bool eval(bool (*f)()) { return (*f)(); }
bool eval(void (*f)()) { (*f)(); return true; }
template <typename Type>
bool eval(Type* obj, bool (Type::*method)()) { return (obj->*method)(); }
template <typename Type>
bool eval(Type* obj, void (Type::*method)()) { (obj->*method)(); return true; }
和通用类来携带各种对象和方法。感谢 Mr.Ree 提供的代码将我推向了这个方向!
要在编译时检测 void 返回值,标准技巧是重载operator,
。逗号运算符最酷的一点是它可以采用 void 参数,在这种情况下,它默认为内置参数operator,
。在代码中:
template <typename> tag {};
template <typename T>
tag<T> operator,(T, tag<void>);
Now, expr, tag<void>()
有类型tag<typeof(expr)>
即使expr
类型为 void。然后你可以用常用的技巧来捕捉这个问题:
char (&test(tag<void>))[1];
template <typename T> char (&test(tag<T>))[2];
template <typename F>
struct nullary_functor_traits
{
static const bool returns_void = sizeof(test((factory()(), tag<void>()))) == 1;
private:
static F factory();
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)