【问题标题】:Is it possible to use specialize a template with no argument?是否可以使用没有参数的专门模板?
【发布时间】:2016-11-04 16:09:35
【问题描述】:

我自己做这个语法,因为我认为以后更方便。

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&lt;&gt;::i 是可能的。

而且我也知道如何使用 aliasusing

我只是问这可能吗?与其对我说 NO,不如让我 downvote

【问题讨论】:

  • 如果我理解正确的话。当然可以,但您仍然需要使用my&lt;&gt;::i 等。
  • 究竟什么是完成投票
  • @skypjack,谢谢。我不是英语母语,也只是学习它,我也使用我的平板电脑。

标签: c++ templates


【解决方案1】:

您可以将您的 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&lt;&gt;::i

如果您绝对希望 my::imy&lt;int&gt;::vec 正确,那么据我所知,没有办法做到这一点。

【讨论】:

  • 编译器说:error: ‘template&lt;class T, typename almost_identity&lt;U&gt;::type value&gt; struct my’ used without template parameters
  • @k-5 你从哪里得到U
  • @k-5 您需要使用 my 和 GillBates 建议的模板括号,即 my&lt;&gt;::i
  • @k-5 我按要求回答了这个问题。我想你可以责怪语言障碍。也就是说,我不明白这有什么理由反对。
  • @k-five 当你下来时再次阅读答案和 cmets - 这里没有人试图打扰你,而是帮助你
【解决方案2】:

你愿意接受一个稍微不同的名字,你可以使用一个using声明来做类似的事情:

using myy = my<int>;

然后将您的类型称为:

myy::i

【讨论】:

  • 对不起,我的朋友,我可以自己使用 aliasusing,但我希望使用相同的名称 my 进行此操作,请注意,如果不可能,请说不
  • @k-5 好吧,所以没有
猜你喜欢
  • 2017-01-16
  • 1970-01-01
  • 1970-01-01
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-07
相关资源
最近更新 更多