5

我目前正在尝试类模板编程,并且在将命名的 lambda 作为其参数传递时遇到了这种奇怪的行为,我无法理解。有人可以解释为什么下面的(1)和(2)不起作用吗?

template<typename Predicate>
class Test{
public:
    Test(Predicate p) : _pred(p) {}
private:
    Predicate _pred;
};

int main(){
    auto isEven = [](const auto& x){ return x%2 == 0; };

    // Working cases
    Test([](const auto& x){ return x%2 == 0; });
    Test{isEven};
    auto testObject = Test(isEven);

    // Compilation Error cases
    Test(isEven); // (1) Why??? Most vexing parse? not assigned to a variable? I cant understand why this fails to compile.
    Test<decltype(isEven)>(isEven); // (2) Basically same as (1) but with a workaround. I'm using c++17 features, so I expect automatic class parameter type deduction via its arguments

    return 0;
};

编译器错误消息:(1)和(2)相同

cpp/test_zone/main.cpp: In function ‘int main()’:
cpp/test_zone/main.cpp:672:16: error: class template argument deduction failed:
     Test(isEven);
                ^
cpp/test_zone/main.cpp:672:16: error: no matching function for call to ‘Test()’
cpp/test_zone/main.cpp:623:5: note: candidate: template<class Predicate> Test(Predicate)-> Test<Predicate>
     Test(Predicate p): _p(p){
     ^~~~
cpp/test_zone/main.cpp:623:5: note:   template argument deduction/substitution failed:
cpp/test_zone/main.cpp:672:16: note:   candidate expects 1 argument, 0 provided
     Test(isEven);
                ^

请原谅我的格式,并编译错误消息片段,因为它与确切的行不匹配。我正在使用 g++ 7.4.0,并使用 c++17 功能进行编译。

4

2 回答 2

4

在 C++ 中,您可以将变量声明为

int(i);

这与

int i;

在你的情况下,线条

Test(isEven);
Test<decltype(isEven)>(isEven);

就像您声明变量一样编译isEven。令我惊讶的是,您的编译器发出的错误消息与我希望看到的如此不同。

你也可以用一个简单的类来重现这个问题。

class Test{
   public:
      Test(int i) : _i(i) {}
   private:
      int _i;
};

int main(){

   int i = 10;

   Test(i);
   return 0;
};

我的编译器 g++ 7.4.0 出错:

$ g++ -std=c++17 -Wall    socc.cc   -o socc
socc.cc: In function ‘int main()’:
socc.cc:15:11: error: conflicting declaration ‘Test i’
     Test(i);
           ^
socc.cc:10:9: note: previous declaration as ‘int i’
     int i = 10;
于 2019-06-03T04:17:16.923 回答
2

正如您所说,这是一个最令人头疼的解析问题;Test(isEven);正在尝试用 name 重新定义一个变量,isEven对于Test<decltype(isEven)>(isEven);.

正如您所展示的,您可以使用{}而不是(),这是自 C++11 以来的最佳解决方案;或者您可以添加额外的括号(使其成为函数式强制转换)。

(Test(isEven));
(Test<decltype(isEven)>(isEven)); 

居住

于 2019-06-03T04:20:03.177 回答