c++ - 是否可以使用不带参数的专门化模板?

标签 c++ templates

我自己写了这个语法,因为我认为它对以后更方便。

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是可能的。

而且我也知道如何使用 aliasusing

我只是问这可能吗?你没有对我说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;
};

demo

这将允许您使用 my<>::i .

如果你绝对想要my::imy<int>::vec是正确的,据我所知,没有办法做到这一点。

关于c++ - 是否可以使用不带参数的专门化模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40427196/

相关文章:

c++ - 将类从应用程序解决方案移到静态库解决方案会产生无法解决的外部符号链接(symbolic link)错误

C++如何使用参数化构造函数实例化对象?

c++ - CUDA:Mark Harris 的并行缩减样本不只是对每个线程 block 求和吗?

c++ - 模板特化语法错误​​?没有把握

c++ - 模板和非模板成员函数指针的类型标识之间的区别

C++ 理解 vector 创建的 size_t 行为

c++ - 模板方法未实例化

c++ - C++ : Compile Error: expected initializer before ‘<’ token

从模板实例化后声明的模板函数选择候选者调用的 C++ 模板重载决策

templates - 允许 vi 节点接受任何输入类型