我最近开始使用右值参考,我遇到了一个我不明白为什么他们按照他们的方式工作的情况.
我正在尝试确定一个类型是否可以拥有begin并end调用它.下面的代码给出了预期的结果,如果我改变foo把它通过值或const引用参数,但我不知道为什么使用右值引用,我想知道是否有人能告诉我为什么当它不工作.
#include <vector>
#include <type_traits>
#include <iostream>
template<class Container>
auto begin(Container &&c) -> decltype(c.begin()) { return c.begin(); }
template<class Container>
auto end(Container &&c) -> decltype(c.end()) { return c.end(); }
template<class T, size_t size>
T *begin(T (&array)[size]) { return (&array[0]); }
template<class T, size_t size>
T *end(T (&array)[size]) { return (&array[0] + size); }
template <typename T>
struct has_begin_end
{
typedef char true_type;
typedef char false_type[2];
template <typename U> static true_type& test(decltype(begin(*((U*)0))) *b = 0,
decltype(end(*((U*)0))) *e = 0);
template <typename U> static false_type& test(...);
enum { value = (sizeof(true_type) == sizeof test<T>(0)) };
};
template<class T>
void foo(T &&t)
{
std::cout << has_begin_end<T>::value << std::endl;
}
int main()
{
std::vector<int> v = {1, 2};
std::cout << has_begin_end<std::vector<int> >::value << std::endl;
std::cout << has_begin_end<int>::value << std::endl;
foo(v);
foo(123);
}
Run Code Online (Sandbox Code Playgroud)
这是因为当使用左值调用foo时,T被推导为左值引用类型.尝试:
has_begin_end<typename remove_reference<T>::type>::value
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
321 次 |
| 最近记录: |