类方法的结果类型
Result type of a class method?
考虑以下示例:
#include <iostream>
#include <numeric>
#include <array>
#include <type_traits>
// Array: I cannot modify this class
template<typename T, unsigned int N>
class Array
{
public:
Array() : _data() {std::iota(std::begin(_data), std::end(_data), 0);}
inline T& operator[](unsigned int i) {return _data[i];}
inline const T& operator[](unsigned int i) const {return _data[i];}
static constexpr unsigned int size() {return N;}
protected:
T _data[N];
};
// Test function: How to get the type returned by T::operator[](unsigned int) ?
template<typename T>
typename std::result_of<T::operator[](const unsigned int)>::type f(const T& x)
{
return x[0];
}
// Main
int main(int argc, char* argv[])
{
Array<double, 5> x;
std::array<double, 5> y = {{0}};
for (unsigned int i = 0; i < x.size(); ++i) std::cout<<x[i]<<std::endl;
for (unsigned int i = 0; i < y.size(); ++i) std::cout<<y[i]<<std::endl;
std::cout<<f(x)<<std::endl;
std::cout<<f(y)<<std::endl;
return 0;
}
是否有办法得到T::operator[](unsigned int)
返回的类型?
目前,g++表示:argument in position '1' is not a potential constant expression
最简单的方法是使用尾随返回类型,它允许您访问函数参数,以及decltype
,它允许您获得表达式的类型。
template<typename T>
auto f(const T& x) -> decltype(x[0])
{
return x[0];
}
您所需要的只是使用语法auto foo(...) -> T
的新样式的函数定义。看
相关文章:
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- Static_cast转换为错误的数据类型,但结果仍然正确?
- 为什么'typeid(x) == typeid(y)'的计算结果为 true,其中 'x' 和 'y' 分别是 T 和 T& 类型的 id-表达式?
- 为什么 Clang 和 GCC 中两个无符号整数之和的结果类型不同
- C++ 模板结果类型
- C++,概念不适用于无符号整数作为结果类型?
- std::chrono::duration::count函数的实际结果类型是什么
- 设计自己的结果/两者之一:是否应该始终指定成功类型和错误类型
- 如何获得将两种不同类型的相乘的结果类型?
- 为什么 std::when_any 使用 std::tuple 而不是 std::vector 作为其结果类型?
- 什么是在C 中存储结果INT*的最佳数据类型
- 在不同类型的向量上使用 std::remove 的不同结果
- boost::variant 当 bool 显示为可能的类型时,会给出错误的结果
- libclang 为类型限定符给出错误的结果
- VIM:执行复杂文件类型的脚本和显示结果
- GCC 9.1 返回 void& 作为显式析构函数调用的结果类型。这是一个错误吗?
- 使用枚举确定返回结果的类型(使用宏的黑客)
- 根据运算符推断模板返回类型:结果
- 类型结果之间的意外差异