1

在花费 1 或 2 个小时来隔离编译错误后,该编译错误被元编程混乱所包围,生成糟糕的编译消息,这里有一个最小且简单的示例来说明我的问题:

#include <iostream>
#include <type_traits>
#include <array>
#include <utility>
#include <tuple>

template <class Crtp, class... Types>
struct Base
{
    Base(const Types&... rhs) : 
        data(std::forward_as_tuple(rhs...)) {;}
    std::tuple<Types...> data;
};

struct Derived 
: public Base<Derived, std::array<double, 3>>
{
    template <class... Args> 
    Derived(Args&&... args) :
        Base<Derived, std::array<double, 3>>(std::forward<Args>(args)...) {;}
};

int main(int argc, char* argv[])
{
    Derived a(std::array<double, 3>({{1, 2, 3}})); 
    Derived b(a);
    Derived c(std::array<double, 3>()); 
    Derived d(c); // Not working : why ?
    return 0;
}

这是用 g++ 4.8.1 编译的,我不明白为什么当我尝试复制而不是复制时编译cda抱怨b.

这是错误:

main.cpp: In instantiation of ‘Derived::Derived(Args&& ...) [with Args = {Derived (&)(std::array<double, 3ul> (*)())}]’:
main.cpp:28:16:   required from here
main.cpp:20:73: error: no matching function for call to ‘Base<Derived, std::array<double, 3ul> >::Base(Derived (&)(std::array<double, 3ul> (*)()))’
         Base<Derived, std::array<double, 3>>(std::forward<Args>(args)...) {;}
                                                                         ^
main.cpp:20:73: note: candidates are:
main.cpp:10:5: note: Base<Crtp, Types>::Base(const Types& ...) [with Crtp = Derived; Types = {std::array<double, 3ul>}]
     Base(const Types&... rhs) : 
     ^
main.cpp:10:5: note:   no known conversion for argument 1 from ‘Derived(std::array<double, 3ul> (*)())’ to ‘const std::array<double, 3ul>&’
main.cpp:8:8: note: constexpr Base<Derived, std::array<double, 3ul> >::Base(const Base<Derived, std::array<double, 3ul> >&)
 struct Base
        ^
main.cpp:8:8: note:   no known conversion for argument 1 from ‘Derived(std::array<double, 3ul> (*)())’ to ‘const Base<Derived, std::array<double, 3ul> >&’
main.cpp:8:8: note: constexpr Base<Derived, std::array<double, 3ul> >::Base(Base<Derived, std::array<double, 3ul> >&&)
main.cpp:8:8: note:   no known conversion for argument 1 from ‘Derived(std::array<double, 3ul> (*)())’ to ‘Base<Derived, std::array<double, 3ul> >&&’
4

3 回答 3

3

这是最令人头疼的解析

Derived c(std::array<double, 3>());

是一个函数的声明,c它返回 aDerived并接受一个类型为指针的未命名参数,指向不接受参数并返回的函数std::array<double, 3>。因此Derived d(c)尝试Derived从函数调用构造函数c。这就是 GCC 在这里所说的:

main.cpp: In instantiation of ‘Derived::Derived(Args&& ...) [with Args = {Derived (&)(std::array<double, 3ul> (*)())}]’:

尝试这个:

Derived c{std::array<double, 3>{}};
于 2013-07-05T10:55:29.997 回答
3

适用于:

Derived c(std::array<double, 3> {});

编译器考虑参数

Derived c(std::array<double, 3>());

成为一个函数。

clang 对此给出警告:
!!warning: parentheses were disambiguated as a function declarator.

于 2013-07-05T11:00:53.063 回答
0

首先使您的 Derived 构造函数显式。如果这无助于添加复制构造函数,但我认为不需要

于 2013-07-05T10:43:18.990 回答