部分模板专用化 c++ 未完全使用不完整类型无效
Invalid use of incomplete type for partial template specialization c++
我正在尝试专门化一个类方法foo()
。这适用于完整的模板专用化。但是,这不适用于部分模板专用化。
这里是在GCC和Clang上编译良好的示例代码:
#include <iostream>
#include <string>
template <typename Key, typename Value>
struct SimpleKey {
Key key;
Value value;
void foo() const {
std::cout << "base" << std::endl;
}
};
/*
// Uncomment this and it won't work !
template<typename Key>
void SimpleKey<Key, std::string>::foo() const {
std::cout << "partial" << std::endl;
}
*/
template<>
void SimpleKey<int, std::string>::foo() const {
std::cout << "full" << std::endl;
}
int main() {
SimpleKey<double, std::string> key1{1.0,"key1"};
key1.foo();
SimpleKey<int, std::string> key2{1,"key2"};
key2.foo();
}
取消注释相关代码时,我收到的 Clang 和 GCC 错误是:
错误:无效使用不完整的类型"struct SimpleKey>" void SimpleKey::foo() const {
我应该怎么做才能让部分模板专业化以"最少"的努力正常工作?
可以显式专用化类模板的特定隐式实例化的成员函数。但这是部分专业化所不允许的。如果您不想编写完整的部分专用化,则可以考虑使用标记调度:
private:
void foo(std::true_type /*value_is_string*/) const { /* "partial" */ }
void foo(std::false_type /*value_is_string*/) const { /* "base" */ }
public:
void foo() const { return foo(std::is_same<Value, std::string>()); }
或将foo()
重构为您部分专用的基类模板。
这不可能直接。(可惜了,这个语法很好)但是你可以做这样的事情:
namespace detail {
inline void f_(int i) { /* spé for int */}
inline void f_(long i) { /* spé for long*/}
/* other spe... */
}
template<class T>
struct Foo{
void f(T arg) { detail::f_(arg);}
};
它没有那么直接,但仍然易于阅读。
相关文章:
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 用callgrind追踪不必要的副本
- 由于无效的 ValidateRgn() 子窗口不会收到WM_PAINT消息
- '{'标记之前的预期类名,然后在预声明时无效使用不完整的类型'class class_name'
- (如何)获取有关某个 C++Year 的已弃用/不推荐的功能/构造的编译器警告
- 缓冲区用不需要的数据填充 char 数组中的最后一个空格
- 我收到错误"变量类型不完整"无效,我找不到问题所在
- 如果迭代器的迭代器永远不会无效,则是STD :: MAP访问线程安全
- 我们可以用不混合而缝制图像
- 参数类型不匹配(无效*)
- 带有 CUDA 的 CMake:用不必要的引号 (\) 括起来的 ccbin
- 为什么我的程序设计为用完 RAM 和 CPU 不使用所有 RAM 和 CPU?
- 用不重复的随机数填充向量.为什么不工作
- 如何在不陷入无效输入的情况下重复此操作
- 瓦尔格林德找不到无效的写入
- 有没有办法用不变语法获得当前的类类型?
- 用c++编译C代码:无效转换
- 标准容器模板可以用不完整类型实例化吗?
- 内联调用不太可能失败,代码大小将增长[-Winline],但不使用内联
- 为什么push_back签名是无效的push_back(const value_type&val)而不是无效push_back(value_type val)?