![](/img/trans.png)
[英]How can I use different struct as template argument in a template function?
[英]How can I define different struct members for different template parameters?
如何为不同的template
参数定义不同的结构成员? 我尝试通过以下方式使用requires
关键字:
template<typename T> requires std::is_void_v<T>
class Foo
{
public:
void Bar()
{
}
};
template<typename T>
class Foo
{
public:
T* Bar()
{
if (!m_T)
m_T = new T();
return m_T;
}
private:
T* m_T{};
};
但这不会编译:
Foo<T> Foo(void)
: 无法推断T
的template
参数Foo<T> Foo(Foo<T>):
需要 1 个参数 - 提供 0Foo
: requires 子句与声明不兼容这种行为在 C++ 20 中甚至可能吗?
虽然requires
在一般情况下可能很有用,但它在精确匹配一种模板参数类型方面的优势被负面因素所抵消。
自 C++03 甚至 C++98 以来,类型的模板特化已经成为可能:
template<typename T>
class Foo;
template<>
class Foo<void>
{
public:
void Bar()
{
}
};
template<typename T>
class Foo<T>
{
public:
T* Bar()
{
if (!m_T)
m_T = new T();
return m_T;
}
private:
T* m_T{};
};
关于第三个错误:
您不能在同一个 scope 中声明两个具有相同名称的主 class 模板。 您只能声明一个主模板,然后为其添加部分或显式特化。 部分专业化需要比主要模板更专业化。
部分特化的语法与您使用的(主模板的语法)略有不同,主模板的声明必须在部分特化之前:
// primary class template
template<typename T>
class Foo
{
public:
T* Bar()
{
if (!m_T)
m_T = new T();
return m_T;
}
private:
T* m_T{};
};
// partial specialization with (more) constraints
template<typename T> requires std::is_void_v<T>
class Foo<T> // <- Additional template argument list for partial specialization
{
public:
void Bar()
{
}
};
其他错误消息要么是此问题的结果,要么是由于模板在您未显示的其他地方的使用方式问题引起的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.