如何确定给定数组类型的下标运算符的返回类型是否带有boost?
问题描述:
如果我想确定使用boost的数组(T)的下标运算符返回的类型,我需要使用哪种类型的签名?请注意,我将使用它的数组不包含typedefs并且是第三方。如何确定给定数组类型的下标运算符的返回类型是否带有boost?
例子。我想确定:
SomeArray<int> tmp(1);
int& somevalue = tmp[0]; //would equate
typename subscript_result<SomeArray<int> >::type somevalue = tmp[0];
喜欢的东西
template<class T>
struct subscript_result
{
typedef boost::result_of<T::operator[](typename T::difference_type)>::type type;
};
?我一直在操作符[]中输入签名。 :|
谢谢!
答
也许你可以使用BOOST_TYPEOF
/BOOST_TYPEOF_TPL
:http://www.boost.org/doc/libs/1_35_0/doc/html/typeof/refe.html#typeof.typo
BOOST_TYPEOF(tmp[0]) i;
在C++ 0x中,你应该能够使用decltype(tmp[0]) i;
在回答评论。或许你可以欺骗它不能去除常量和参考用类似的东西:
#include <boost/typeof/typeof.hpp>
template <class T>
struct identity
{
typedef T type;
};
template <class T>
struct subscript_result
{
template <class Result, class Obj, class Arg>
static identity<Result> get_subscript_type(Result (Obj::*)(Arg));
typedef BOOST_TYPEOF(get_subscript_type(&T::operator[])) aux;
typedef typename aux::type type;
};
#include <vector>
#include <iostream>
template <class Container>
void foo(Container& c)
{
typename subscript_result<Container>::type t = c[0];
++t;
}
int main()
{
//prove that foo gets a reference to vector<int>
std::vector<int> vec(1);
foo(vec);
std::cout << vec[0] << '\n';
}
你可能还需要拿出一些为常量重载,以及投特数组/指针。
看起来像是BOOST_TYPEOF/_TPL包含引用和cv-qualification作为结果的一部分可能是有用的。如此接近,该死的。 – Geoff 2010-09-14 14:12:38
@Geoff不能使用type_traits'is_const','is_volatile'和'is_reference'来查找引用和cv-qualification?然后使用它作为模板特化的一部分来声明类型为typedef typename const BOOST_TYPEOF(get_subscript_type(&T :: operator []))type type;或typedef typename BOOST_TYPEOF(get_subscript_type(&T :: operator []) ):: type & type;'? – KitsuneYMG 2010-09-14 15:05:29