0

我在程序中使用可变参数模板,但出现了意外错误。我隔离了错误,我对此感到震惊:

#include<cctype> 
#include<iostream> // try to delete this line

class A 
{ 
    public: 
        void constructor() 
        {   } 

        template<typename... Args> 
        void constructor( int (*f)(int), Args... args ) 
        { 
            // process( f ) 
            constructor( args... ); 
        } 

        template<typename... Args> 
        A( Args... args ) 
        { 
            constructor( args... ); 
        } 
}; 

int main() 
{ 
    A a; 
    a.constructor( std::isspace ); // ok

    A b( std::isspace ); // error

    return 0; 
}

如果删除“#include iostream”行,源代码编译正常。但是,如果您输入这一行,编译器会抛出错误:

prov.cpp: In function ‘int main()’:
prov.cpp:32:22: error: no matching function for call to ‘A::A(<unresolved overloaded function type>)’
prov.cpp:32:22: note: candidates are:
prov.cpp:18:7: note: A::A(Args ...) [with Args = {}]
prov.cpp:18:7: note:   candidate expects 0 arguments, 1 provided
prov.cpp:4:7: note: constexpr A::A(const A&)
prov.cpp:4:7: note:   no known conversion for argument 1 from ‘&lt;unresolved overloaded function type>’ to ‘const A&’
prov.cpp:4:7: note: constexpr A::A(A&&)
prov.cpp:4:7: note:   no known conversion for argument 1 from ‘&lt;unresolved overloaded function type>’ to ‘A&&’

我正在使用这个 g++ 版本:g++ (Ubuntu/Linaro 4.7.2-11precise2) 4.7.2,我正在使用以下标志进行编译:g++ -Wall -pedantic -std=c++11 prov.cpp -o prov

我不明白为什么编译器会抛出这个错误。这是一个可能的错误吗?

4

2 回答 2

3

这不是编译器错误,甚至不是可变参数模板的问题,std::isspace只是重载。直接调用时.constructor,第一个参数int (*f)(int)为编译器提供了足够的信息来选择正确的重载,而泛型参数则没有。这很容易用一个例子来证明:

// our std::isspace
void foo(int){}
void foo(double){}

void test1(void (*f)(int)){}

template<class T>
void test2(T v){}

int main(){
  test1(foo); // compiles, compiler sees you want the 'int' overload
  test2(foo); // error, compiler has no clue which overload you want
              // and which type to deduce 'T' as
}

您可以通过两种方式解决此问题:

int (*f)(int) = std::isspace; // assign to variable, giving the compiler the information
A b(f); // already has concrete type here

// or
A b(static_cast<int(*)(int)>(std::isspace)); // basically the same as above, in one step
于 2013-03-15T14:12:37.823 回答
2

问题是它<cctype>定义了一个函数isspace,但添加<iostream>了另一个重载,因为isspace它是从<locale>. 来自的一个<cctype>

int isspace( int ch );

来自的一个<locale>

template< class charT >
bool isspace( charT ch, const locale& loc );

两者都包含在内,std::isspace变得模棱两可,因此您的代码失败。仅当您通过真实的 ctor (而不是constructor)路由它时才可见,因为那时编译器无法决定转发什么。OTOH,该方法constructor采用一个参数,该参数已经告诉编译器如何从两个重载中进行选择。

于 2013-03-15T14:19:43.597 回答