问题描述
在这个问题中,我引出了一个特殊的解决方案,其中涉及对模板化别名声明的部分专门化.通用案例在此答案中进行了描述.假设我有一个模板类
In this question I am led to a particular solution which involves partial specializations of templatized alias declarations. The generic case is described in this answer. Suppose I have a template class
template<typename T, ...>
class X {
// ....
};
我不是在让T腾空并专门化其他模板参数的情况下,而是在其他参数取决于T且仅取决于T的情况下.作为一个非常具体的示例(比另一个问题中的示例更易于管理),请考虑模板类
Rather than leaving T free and specializing the other template parameters I am in a situation in which the other arguments depend on T, and on T alone. As a very concrete example (more manageable than the example in the other question) consider a template class
template<typename T, T absVal(T)>
class Number_impl {
private:
T _t;
public:
Number_impl(T t): _t(t) {}
T abs() const {return absVal(_t);}
};
可能的专业是
Number_impl<int, std::abs>;
和
Number_impl<double, std::fabs>;
(我知道有重载的Abs版本,这只是出于说明的目的.如果需要,请参见我的其他示例).
(I know there are overloaded abs versions, this is just for the sake of illustration. See my other example if you want).
理想情况下,我想根据单个参数(类型)定义模板类Number,以使Number< int>等于
Ideally I would like to define a template class Number depending on a single argument, the type, so that Number<int> is equal to
Number_impl<int, std::abs>;
和数字< double>等于
and Number<double> is equal to
Number_impl<double, std::fabs>;
类似以下内容(无效):
Something like the following (which doesn't work):
template<typename T>
using Number = Number_impl<T, nullptr>;
template<>
using Number<int> = Number_impl<int, std::abs>;
template<>
using Number<double> = Number_impl<double, std::fabs>;
有人知道这种方法是否可行,如何实现,或者如何以不同的方式实现吗?
Does anyone know if and how this can be made to work, or how the same can be achieved in a different way?
推荐答案
执行此类操作的正常方法与标准库的处理方法相同-具有可以专门研究的traits类:
The normal way to do this kind of thing is the same way the standard library does it - with a traits class that you can specialise:
#include <iostream>
#include <cmath>
template<typename T> struct NumberTraits;
template<typename T, class Traits = NumberTraits<T>>
class Number {
private:
T _t;
public:
Number(T t): _t(t) {}
T abs() const {
return Traits::abs(_t);
}
};
template<> struct NumberTraits<int>
{
static int abs(int i) {
return std::abs(i);
}
};
template<> struct NumberTraits<double>
{
static double abs(double i) {
return std::fabs(i);
}
};
using namespace std;
auto main() -> int
{
Number<int> a(-6);
Number<double> b(-8.4);
cout << a.abs() << ", " << b.abs() << endl;
return 0;
}
预期输出:
6, 8.4
这篇关于模板化别名声明的部分专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!