当使用auto
关键字时,我如何找出编译器推导出的类型?
示例1:更简单
auto tickTime = 0.001;
这是作为float
还是double?
推导出来的?
示例2:更复杂(这也是我现在头疼的问题):
typedef std::ratio<1, 1> sec;
std::chrono::duration<double, sec > timePerTick2{0.001};
auto nextTickTime = std::chrono::high_resolution_clock::now() + timePerTick2;
nextTickTime
是什么类型
我遇到的问题是,当我试图向std::cout
发送nextTickTime
时。我得到以下错误:
./main.cpp: In function ‘int main(int, char**)’:
./main.cpp:143:16: error: cannot bind ‘std::basic_ostream<char>’ lvalue to ‘std::basic_ostream<char>&&’
std::cout << std::setprecision(12) << nextTickTime << std::endl; // time in seconds
^
In file included from /usr/include/c++/4.8.2/iostream:39:0,
from ./main.cpp:10:
/usr/include/c++/4.8.2/ostream:602:5: error: initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<double, std::ratio<1l, 1000000000l> > >]’
operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
发布于 2016-08-09 06:09:45
一个不需要任何事先助手定义的lo-fi技巧是:
typename decltype(nextTickTime)::_
无论nextTickTime
是什么类型,编译器都会抱怨_
不是它的成员。
发布于 2016-08-08 12:56:42
下面是一个使用boost::core::demangle
在运行时获取类型名称的typeid
版本。
#include <string>
#include <iostream>
#include <typeinfo>
#include <vector>
using namespace std::literals;
#include <boost/core/demangle.hpp>
template<typename T>
std::string type_str(){ return boost::core::demangle(typeid(T).name()); }
auto main() -> int{
auto make_vector = [](auto head, auto ... tail) -> std::vector<decltype(head)>{
return {head, tail...};
};
auto i = 1;
auto f = 1.f;
auto d = 1.0;
auto s = "1.0"s;
auto v = make_vector(1, 2, 3, 4, 5);
std::cout
<< "typeof(i) = " << type_str<decltype(i)>() << '\n'
<< "typeof(f) = " << type_str<decltype(f)>() << '\n'
<< "typeof(d) = " << type_str<decltype(d)>() << '\n'
<< "typeof(s) = " << type_str<decltype(s)>() << '\n'
<< "typeof(v) = " << type_str<decltype(v)>() << '\n'
<< std::endl;
}
它会在我的系统上打印以下内容:
typeof(i) = int
typeof(f) = float
typeof(d) = double
typeof(s) = std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >
typeof(v) = std::vector<int, std::allocator<int> >
发布于 2016-08-08 11:05:57
typeid大多数时候都可以用来获取变量的类型。它依赖于编译器,我见过它产生奇怪的结果。g++默认开启RTTI端,不确定在Windows端。
#include <iostream>
#include <typeinfo>
#include <stdint.h>
#include <chrono>
#include <ctime>
typedef std::ratio<1, 1> sec;
int main()
{
auto tickTime = .001;
std::chrono::duration<double, sec > timePerTick2{0.001};
auto nextTickTime = std::chrono::high_resolution_clock::now() + timePerTick2;
std::cout << typeid(tickTime).name() << std::endl;
std::cout << typeid(nextTickTime).name() << std::endl;
return 0;
}
./a.out | c++filt
double
std::__1::chrono::time_point<std::__1::chrono::steady_clock, std::__1::chrono::duration<long long, std::__1::ratio<1l, 1000000000l> > >
https://stackoverflow.com/questions/38820579
复制相似问题