2016-04-15 52 views
3

在泛型编程的精神,我创建了下面的代码:是否存在使用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. 

从我可以通过静态地址告诉,这将产生两个不同的功能,所以在我看来就像一个模板速记,一种。我的直觉是,要维护的一个功能比多个功能要好,但是,除了要注意非共享静态变量,我是否错过了一些可能使其成为糟糕选择的东西,而不是多个函数定义?

+0

只能在通用lambdas中使用'auto' ...对于函数,使用模板 – WhiZTiM

+2

这是一个非标准的扩展,模板的简写,显然[可能会添加到C++ 17标准]( http://stackoverflow.com/questions/25879705/is-auto-as-a-parameter-in-a-regular-function-a-gcc-4-9-extension)。不是C++的一部分14。 – HostileFork

+2

@HostileFork不会在C++中17。 – Barry

回答

8

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

void Call(auto & fp) 

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

-1

这是不可能的,是主要的缺陷。

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

+0

这对于通用lambdas来说正是* any *类型。 – SergeyA

+2

@SergeyA如果'Call'是一个通用的lambda,那么这将是相关的? – Barry

+0

@SergeyA:它不是 - 它会被推断的任何类型所取代。我试图做的一点(确实非常糟糕)是,像某些新手想象的那样,“auto”本身不是一种类型。一个对象不能“自动”。我强烈怀疑这个问题的核心是误解。 –

相关问题