c++ - 使用 auto 作为参数是否有负面影响?

标签 c++ templates c++14 auto

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

#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.

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

最佳答案

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

void Call( auto & fp )

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

关于c++ - 使用 auto 作为参数是否有负面影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36651568/

相关文章:

c++ - 将类对象指针传递给用于初始化 C++ 的函数

c++ - 代码中使用 "sprintf"是否需要释放内存?

c++ - Typedef 模板参数

c++ - 编译时的模板和 constexpr 推导取决于编译器和优化标志

c++ - 对指针数组的引用

c++ - `core constant expression` 与 `constant expression`

C++ 在新的中转换指针?

c++ - 使用循环(不是迭代器)从 vector 中删除指针

c++ - 为什么 is_constructible 声称某些东西不是可构造的?

c++ - 尝试将记录中的数据读入程序时难以捉摸的错误(C++)