【发布时间】:2019-05-03 11:52:57
【问题描述】:
我正在努力寻找最好的方法来拥有一种“对象”,它可以是专门的,也可以“链接”到另一种类型。
例如,您不能专门化一个类以使其成为简单的 int,并且您不能使用关键字 using 来专门化类。
我的解决方案如下:
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
有没有办法实现我想要的?可以同时更改 doSomething 或 A 实现。
【问题讨论】:
-
您的代码中没有模板特化。我不清楚这里的总体目标是什么超出了您展示的确切实现。我假设您希望以后能够换出
AImpl,但不清楚您为什么不直接通过using A = AImpl1<...>这样做。 -
也就是说
AHelper的意义何在?在您显示的代码中似乎没有必要,因此您能否扩展示例以包含AHelper部分的用途(这似乎是问题的核心)? -
@MaxLanghof 没错,代码已更改。我希望现在更清楚了
-
我添加了一些其他代码来向您展示替代方案。
-
由于显而易见的原因,您省略了
doSomething的实现,但是对于基本类型和类类型,它的工作方式完全相同的代码是什么?对于普通整数,在这样的函数中如何需要Category?
标签: c++ c++11 templates template-meta-programming template-argument-deduction