How do I say:
template<typename T>
class X {
// if T has method x(), define
// Y x() { return t.x() }
开发者_开发百科 T t;
};
Just define it.
If X::x
isn't called, then T::x
doesn't have to exist either. If X::x
is called and T::x
doesn't exist, the error message will point to the use of X::x
. Most compilers would use wording along the lines of: "Unknown identifier x
while compiling Y X<Something>::x(void)
within this context: whatever called X::x() for a Something that doesn't support it".
EDIT: Since you're using C++0x, by all means use decltype:
template<typename T>
class Forwards {
T t;
public:
decltype(this->t.x()) x() { return this->t.x(); }
};
I'm not 100% sure about whether to use decltype(T::x())
, decltype(t.x())
, or decltype(this->t.x())
, but I'm pretty sure this should work. If t
doesn't supply x
, then the Forwards::x()
function wouldn't be able to be instantiated. This still isn't perfect forwarding, since you need to know the argument list a-priori, but now you can deal with return type variation.
精彩评论