gpt4 book ai didi

c++ - 构造函数中的模板冲突

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:52:02 24 4
gpt4 key购买 nike

我有一个结构定义如下:

struct A : public B, public C
{
A(const B& b) : B(b), C()
{}

template<typename... Args>
A(Args&&... args) : B(), C(std::forward<Args>(args)...)
{}
};

int main()
{
B b;

A sample1(b);
A sample2(3); // For example, B has a B(int) constructor.
}

这不能正常工作,因为 A(b) 尝试使用第二个构造函数(非常量引用是首选选项,第一个构造函数是常量引用),但是 B 没有任何 B(A&)

此外,我想为 B 添加一个 move 构造函数:

struct A : public B, public C
{
A(const B& b) : B(b), C()
{}

A(B&& b) : B(std::move(b)), C()
{}

template<typename... Args>
A(Args&&... args) : B(), C(std::forward<Args>(args)...)
{}
};

现在,最后一步是融合前两个构造函数:

struct A : public B, public C
{
template<typename fw_B>
A(fw_B&& b) : B(std::forward<fw_B>(b)), C()
{}

template<typename... Args>
A(Args&&... args) : B(), C(std::forward<Args>(args)...)
{}
};

问题:如果第一个版本导致冲突,那么最后一个版本(我的最终目的)很明显它也不起作用。我怎样才能实现这个目标?

最佳答案

一个可能的解决方案是使用 std::enable_ifstd::is_convertible如果参数类型 b 可转换为 B,则仅包含第一个构造函数:

template <
class fw_B,
class = typename std::enable_if<std::is_convertible<fw_B, B>::value, T>::type>
A(fw_B&& b)

例如:

#include <iostream>
#include <type_traits>

struct B
{
B() {}
B(int) {}
};

struct C {};

struct A : B, C
{
template <
class T,
class = typename std::enable_if<std::is_convertible<T, B>::value, T>::type>
A(T&& t) { std::cout << "A(T&&)\n"; }

template <class... TArgs>
A(TArgs&&... targs) { std::cout << "A(TArgs&&)\n"; }
};

int main()
{
B b;

A a1(b);
A a2(4);
A a3("hello");

return 0;
}

输出:

A(T&&)A(T&&)A(TArgs&&)

参见 http://ideone.com/xJEjic 的演示.

关于c++ - 构造函数中的模板冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14685101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com