我自己写了这个语法,因为我认为它对以后更方便。
temolate<typename U> struct identity{typedef U type;};
temolate<typename T, typename identity<T>::type value=0> struct my{
typedef std::vector<T> vec;
typedef std::array<T,value> arr;
typedef std::set<T> set;
// and so forth
};
我用它:
int main(){
my<int>::vec v; // okay
my<int,3>::arr a; // okay
// and so forth
}
但我也想这样做语法:
(专注于上面的我的)
template<??????????> // what should I do here?
struct my<?????????>{ // or may be here
typedef int i;
typedef float f;
typedef double d;
// and so forth;
}
这样我就可以做到:
int main(){
my::i a; // for int, what should I do?
my::f b; // for float, and
my::d c; // for double, and
// AND I ALSI CAN
my<int>::vec v; // already I know
my<int,3>::arr a; // and know
}
这可能吗?
我在这里看到:
Default template parameter partial specialization
在我问之前。所以我知道my<>::i
是可能的。
而且我也知道如何使用 alias 和 using
我只是问这可能吗?你没有对我说NO,而是让我downvote
最佳答案
您可以默认您的 T
到一个特殊类型(这里是 default_type
)然后专门针对它:
template<typename U> struct almost_identity{typedef U type;};
class default_type{};
template<> struct almost_identity<default_type>{ typedef int type; };
template<typename T = class default_type, typename almost_identity<T>::type value = 0> struct my{
typedef std::vector<T> vec;
typedef std::array<T,value> arr;
typedef std::set<T> set;
// and so forth
};
template<>
struct my<default_type, 0>
{
typedef int i;
typedef float f;
typedef double d;
};
这将允许您使用 my<>::i
.
如果你绝对想要my::i
和 my<int>::vec
是正确的,据我所知,没有办法做到这一点。
关于c++ - 是否可以使用不带参数的专门化模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40427196/