可变参数模板和解决过载歧义的问题

时间:2018-06-24 22:58:09

标签: c++ c++14 variadic-templates initializer-list overload-resolution

编译后,下面的代码生成第12行指出的错误; make_vec似乎不知道该调用构造函数A还是B。

template<int N, typename T = double>
class vec {
    std::array<T, N> buf;
public:
    template <typename... Args, typename = std::enable_if_t<(sizeof...(Args) == N && N > 1)>>
    vec(Args&&... args) : buf({ std::forward<Args>(args)... }) {} // CONSTRUCTOR A
    explicit vec(std::array<T, N>&& arr) : buf(std::move(arr)) {} // CONSTRUCTOR B
};

template <typename... Args>
vec<sizeof...(Args), typename std::common_type<Args...>::type> make_vec(Args&&... args) {
    return vec<sizeof...(Args), typename std::common_type<Args...>::type>({ std::forward<Args>(args)... });
}     // THE LINE ABOVE GENERATES error C2440: '<function-style-cast>': cannot convert from 'initializer list' to 'vec<3,int>'
      //   note: No constructor could take the source type, or constructor overload resolution was ambiguous

int main() {
    auto x = make_vec(1, 2, 3);
    return 0;
}

是否有一种简单的方法可以强制make_vec调用构造函数A,同时保持构造函数A,B和make_vec的签名不变?

0 个答案:

没有答案