【发布时间】:2019-10-04 14:59:53
【问题描述】:
是否可以在编译时根据其参数确定类模板的确切基础?例如。我有一个类模板,它在其构造函数中接受一个参数,我想用另一个参数扩展这个类,将使用另一个构造函数。问题是第二个实例化(带有两个参数)必须具有与带有一个参数的实例不同的基类。我可以使用std::conditional 检测到正确的基类,但问题在于将两个构造函数都放在一个类模板中。例如:
#include <type_traits>
struct X
{
};
struct Y
{
};
struct XX
{
};
struct XY
{
};
template<class T, class V = void>
struct Z: public std::conditional_t<std::is_void_v<V>, XX, XY>
{
Z(T&& t, V&& v)
: XY()
{
// do smth with t and v
}
Z(T&& t)
: XX()
{
// do smth with t
}
};
int main()
{
auto a = Z(X(), Y());
auto b = Z(X()); // <-- this instantiation fails
}
这里Z(X(), Y()) 可以工作,但对于Z(X()),它会因编译错误而失败:
main.cpp: In instantiation of 'struct Z<X, void>':
main.cpp:39:19: required from here
main.cpp:23:5: error: forming reference to void
23 | Z(T&& t, V&& v)
| ^
更新:
尝试使用enable_if 将双参数ctor 设为模板,但它不起作用(与原始代码中的forming reference to void 相同):
template<class = std::enable_if<! std::is_void_v<V>>>
Z(T&& t, V&& v)
: XY()
{
// do smth with t and v
}
【问题讨论】:
-
能否请您添加您尝试实例化模板的行? IE。错误消息中提到的行。
-
在源代码列表中添加注释(第二个实例化一个参数)。
-
这看起来像是在你的 ctor(s) 上使用
std::enable_if的案例。 -
@Matthew:请注意,构造函数必须是 SFINAE 它的模板(即使这样,它也需要一些微妙的技巧来延迟替换失败)。
-
@davis-herring 我希望能够在不指定模板参数的情况下声明
Z的实例。
标签: c++ inheritance c++17