C ++ template:获取没有对象的成员函数的返回类型 [英] C++ template: get return type of member function without an object
问题描述
我有一些类,我不能修改。每个都有一个复制构造函数,至少一个其他构造函数和一个返回一些值的函数 foo()
。我想创建一个类模板,可以从这些类派生,并有一个数据成员与 foo()
(对不起if我有一些术语错了。)
I have a number of classes that I cannot modify. Each has a copy constructor, at least one other constructor, and a function foo()
that returns some value. I want to make a class template that can derive from each of these classes, and has a data member that is the same type as the return type of foo()
(sorry if I've got some of the terminology wrong).
换句话说,我想要一个类模板
In other words, I would like a class template
template<typename T> class C : public T
{
footype fooresult;
};
其中 footype
code> T :: foo()。
where footype
is the return type of T::foo()
.
如果基类都有一个默认的构造函数,
If the base classes all had, say, a default constructor, I could do
decltype(T().foo()) fooresult;
(在GCC中使用C ++ 0x功能),但类没有任何特定的构造函数
(with the C++0x functionality in GCC) but the classes don't have any particular constructor in common, apart from the copy constructors.
GCC也不允许 decltype(this-> foo())
,虽然显然有一个可能性,这将被添加到C ++ 0x标准 - 任何人都知道这是多少可能是?
GCC also doesn't allow decltype(this->foo())
, though apparently there is a possibility that this will be added to the C++0x standard - does anyone know how likely that is?
我觉得应该可以按照 decltype(foo())
或 decltype(T :: foo())
但是那些似乎不工作:GCC给出的形式的错误不能调用成员函数'int A :: foo()'没有对象
。
I feel like it should be possible to do something along the lines of decltype(foo())
or decltype(T::foo())
but those don't seem to work: GCC gives an error of the form cannot call member function 'int A::foo()' without object
.
当然,我可以有一个额外的模板参数 footype
,或者甚至类型<$ c $的非类参数
Of course, I could have an extra template parameter footype
, or even a non-class parameter of type T
, but is there any way of avoiding this?
推荐答案
你不需要记住,因为decltype不会评估它的参数,你可以调用 nullptr
。
You don't need that- remember that since decltype doesn't evaluate its argument, you can just call on nullptr
.
decltype(((T*)nullptr)->foo()) footype;
这篇关于C ++ template:获取没有对象的成员函数的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!