混合别名和模板专业
Mixing aliases and template specializations
我正在尝试找到一种可以使用专业化或"链接"到另一种类型的"对象"的最佳方法。
例如,您不能专业化类使其成为一个简单的INT,并且您不能使用关键字来专门化类。
我的解决方案是:
template<class Category, Category code>
struct AImpl
{};
template<class Category, Category code>
struct AHelper
{
using type = AImpl<Category, code>;
};
template<class Category, Category code>
using A = typename AHelper<Category, code>::type;
template<int code>
void doSomething(A<int, code> object)
{
}
template<>
struct AImpl<int, 5>
{
double a;
};
template<>
struct AImpl<int, 6>
{
int b;
double c;
};
template<>
struct AHelper<int, 7>
{
using type = int;
};
template<class Category, Category code>
struct Alternative {};
template<int code>
void doSomethingAlternative(Alternative<int, code> object)
{
}
这有效,但您需要在Dosomething中指定代码参数,我想避免。
例如:
A<int,7> a7; // This is equivalent to int
a7 = 4;
A<int, 5> a5; // This is equivalent to AImpl<int,5>
a5.a = 33.22;
doSomething(a5); // This does not compile
doSomething<5>(a5); // This compiles but is bulky
Alternative<int,0> alt0;
doSomethingAlternative(alt0); // This compiles and is not bulky
// but you're forced to use class
// specializations only
有没有办法实现我想要的东西?可以更改滴定或A实现。
如果您试图根据所调用的类型自定义doSomething
的行为,则不能使编译器从AHelpr::type
中推论(如前所述(。但是,您可以通过以特征的形式提供自定义点来告诉它。例如:
template<typename T>
void doSomething(T& object)
{
auto code = SmthTriats<T>::code;
}
考虑到SmthTriats
的能力,这是高度扩展的:
template<typename> struct SmthTriats;
template<typename Category, Category code_>
struct SmthTriats<AImpl<Category, code_>> {
static constexpr auto code = code_;
};
template<>
struct SmthTriats<int> {
static constexpr auto code = 7;
};
特征类也允许在模块之外自定义。客户端代码只需要使用自己类型的SmthTriats
专业,只要尊重您与您的特征达成的合同,您的代码将适用于他们。
相关文章:
- 部分定义/别名模板模板参数
- 如何在C++20中创建模板别名的推导指南
- 混合组合和继承的C++问题
- 在混合代码库中将C转换为C++时出现许多包含错误
- 告诉c++编译器该参数没有别名
- D3D11-将混合权重和索引传递到顶点着色器
- boost::spirit::karma 替代生成器,带有 boost::variant 由字符串和字符串别名组成
- 继承模板类中的类型别名
- 别名模板的专业化 C++11 中没有开销的最佳替代方案
- 为什么 GCC 在使用类型别名时处理 const reinterpret_cast不同?
- 类作用域的类型别名"using":[何时]方法中的用法可以先于类型别名?
- 为什么我们不能重复使用具有不同模板参数的别名模板标识符?
- C++模板/别名 - 模板参数列表中参数 1 处的类型/值不匹配
- 如何使用类型别名从模板化类中隐藏模板列表
- C++分数混合比较运算符错误
- 模板模板参数和模板别名:编译器错误?
- 是否可以混合使用SFINAE和模板专业化?
- 使用定义函数模板别名
- 如何在 Python C++ 混合库中调试非确定性分段错误?
- 混合别名和模板专业