【问题标题】:Are there negative ramifications of using auto as a parameter?使用 auto 作为参数是否有负面影响?
【发布时间】:2016-04-15 15:47:10
【问题描述】:

本着泛型编程的精神,我创建了以下代码:

#include <iostream>
#include <functional>

class Functor
{
public:
    void operator()()
    {
        std::cout << "Functor operator called." << std::endl;
    }
};

void Function()
{
    std::cout << "Function called." << std::endl;
}

void Call( auto & fp )
{
    static int i;
    std::cout << "Unified calling..." << &i << std::endl;
    fp();
}

int main( int argc, char ** argv )
{
    Functor functor;
    std::function< void() > function = Function;

    std::cout << "Begin testing..." << std::endl;
    Call( functor );
    Call( function );
    std::cout << "End testing." << std::endl;

    return 0;
}


Compiled with: g++ main.cpp -std=c++14
output:
Begin testing...
Unified calling...0x100402080
Functor operator called.
Unified calling...0x100402090
Function called.
End testing.

从静态地址可以看出,这会产生两个不同的函数,所以在我看来,它就像是模板的简写形式。我的直觉是维护一个函数比维护多个函数要好,但是,除了注意非共享静态变量之外,我是否遗漏了一些可能使其成为糟糕选择的东西,而不是多个函数定义?

【问题讨论】:

  • 你只能在泛型 lambda 中使用 auto... 对于函数,使用模板
  • 它是一个非标准扩展,是模板的简写,显然是likely to be added to the C++17 standard。不是 c++14 的一部分。
  • @HostileFork 不会出现在 C++17 中。
  • @Barry 可能是最好的......但也许你可以告诉那里的答案作者,在适当的参考下从“可能”更新为“不会发生”。
  • @HostileFork 也对该答案发表了评论。

标签: c++ templates c++14 auto


【解决方案1】:

是的,有。当前的 C++ 标准禁止它们。

void Call( auto & fp )

是符合标准的编译器的编译错误。

【讨论】:

    【解决方案2】:

    不可能,是主要缺陷。

    auto 仅表示初始化时的类型推导。它不是“任何”类型。因此,以这种方式使用 auto 意味着您的函数必须是模板。在 C++17 中,这将是可能的,而且 auto 参数确实会自动使函数成为模板(我个人觉得这非常令人困惑,但是哦,好吧)。但现在,没有。

    【讨论】:

    • 对于泛型 lambda,它完全是 any 类型。
    • @SergeyA 如果Call 是一个通用的 lambda,这将是相关的?
    • @SergeyA:不是——它被推导出的任何类型所取代。我试图说明的一点(诚然非常糟糕)是auto 本身并不是一些新手认为的类型。对象不能“成为”auto。我强烈怀疑误解是这个问题的核心。
    • 可能。我现在明白你的意思更好了,比如 auto 不是 boost::any。但是,它仍然不是在使用通用 lambda 进行初始化时的推论,因此该语句并未涵盖所有情况。我认为,如果改写得更清楚,答案会更好。
    • @SergeyA:唯一真正重要的是 OP 的代码格式不正确。
    猜你喜欢
    • 1970-01-01
    • 2023-02-23
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多