如何适当地专注于类模板的功能?
我有一个类,属性
,它具有两个模板参数:属性的类型以及该属性是否是可选的(即可能不存在)。
我编写的代表表示这种逻辑的代码看起来像这样:
#include<type_traits>
#include<optional>
#include<iostream>
template<typename Type, bool Optional>
struct Property {
std::conditional_t<Optional, std::optional<Type>, Type> value;
void do_thing() {
if constexpr (Optional) {
if(value)
std::cout << *value << std::endl;
else
std::cout << "null" << std::endl;
} else {
std::cout << value << std::endl;
}
}
};
template<bool Optional>
void Property<std::string, Optional>::do_thing() {
if constexpr (Optional) {
if(value)
std::cout << "\"" << *value << "\"" << std::endl;
else
std::cout << "null" << std::endl;
} else {
std::cout << "\"" << value << "\"" << std::endl;
}
}
int main() {
Property<int, false> prop1{11};
prop1.do_thing();
Property<int, true> prop2;
prop2.do_thing();
Property<std::string, false> prop3{"Test"};
prop3.do_thing();
}
我需要的一件事是,如果 type> type
是 do_thing()才能更改行为。 > std :: String (或我需要专业的许多其他类型)。
但是,当我尝试编译此代码时,海湾合作委员会抱怨专业化:
<source>:21:48: error: invalid use of incomplete type 'struct Property<std::__cxx11::basic_string<char>, Optional>'
21 | void Property<std::string, Optional>::do_thing() {
| ^
<source>:6:8: note: declaration of 'struct Property<std::__cxx11::basic_string<char>, Optional>'
6 | struct Property {
| ^~~~~~~~
Execution build compiler returned: 1
实施此功能专业化的正确方法是什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正确的方法是首先要首先专门为所需的模板参数进行部分专业化,如下所示:
a>
The correct way would be to first partially specialize the class template itself for the required template arguments as shown below:
Working Demo