我有一个定义如下的结构:
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_if
与 std::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/