【问题标题】:Can ‘auto’ be used in a function declaration?可以在函数声明中使用“auto”吗?
【发布时间】:2018-11-13 07:10:43
【问题描述】:

背景:

我找到了这个方便的随机数生成器,并想为它制作一个头文件: http://www.cplusplus.com/reference/random/

std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(1,6);
auto dice = std::bind ( distribution, generator );
int wisdom = dice()+dice()+dice();

但是,在 C++11 中,返回类型为“auto”的函数声明需要尾随返回类型,以便编译器可以决定类型是什么。 例如:

auto foo(int a, int b) -> decltype(a*b);

问题:

看来我的标题几乎需要与函数本身一样长才能确定类型:

std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(1,6);
auto roll() -> decltype(distribution(generator));

问题:

有没有办法确定使用“auto”类型的函数声明(在标头中)的完整返回类型? 如果不是,我的 dice() 标头应该是什么样的?

【问题讨论】:

    标签: c++11 header-files forward-declaration auto function-declaration


    【解决方案1】:

    由于您使用int 作为std::uniform_int_distribution 的模板类型,因此distribution(generator) 的返回类型为int。除非真实代码也被模板化,否则返回类型可以硬编码为int

    如果真正的代码是模板化的,那么你可以使用std::uniform_int_distributionresult_type成员:

    template<typename T>
    typename std::uniform_int_distribution<T>::result_type roll();
    

    或者只是模板类型本身:

    template<typename T>
    T roll();
    

    【讨论】:

    • 我同意它应该是int,但是每次我尝试使用int时,编译器都会吐出redefinition of 'dice' as different kind of symbol,即使它们应该返回相同的类型,所以我必须做些什么错了。
    • 我需要将函数从“std::bind”重新格式化为 int utils::dice() {return(distribution(generator));}
    猜你喜欢
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    • 2019-02-09
    • 1970-01-01
    • 2020-03-01
    相关资源
    最近更新 更多