C++模板的模板类型特化

huangapple go评论72阅读模式
英文:

C++ specialization of template with templated type

问题

无法编译的理想但不工作的实现:

template<class D> class Dummy{public: D val;};

template<typename T> T foo();

template<> int foo<int>()
{
  return 0;
}

template<typename D> Dummy<D> foo<Dummy<D>>()
{
  return Dummy<D>{};
}

我得到错误信息:不允许非类、非变量的部分特化 'foo<Dummy<D>>'

英文:

I’d like to do a generic function which will be specialized with some types, but I also would like to specialized with templated types, which is not allowed by the compiler.
Is there a way to get around this ?

Ideal not working implementation:

template&lt;class D&gt; class Dummy{public: D val;};
  
template&lt;typename T&gt; T foo();

template&lt;&gt; int foo&lt;int&gt;()
{
  return 0;
}

template&lt;typename D&gt; Dummy&lt;D&gt; foo&lt;Dummy&lt;D&gt;&gt;()
{
  return Dummy&lt;D&gt;{};
}

I get the error non-class, non-variable partial specialization ‘foo&lt;Dummy&lt;D&gt; &gt;’ is not allowed

答案1

得分: 1

如果有人有问题X,解决方案是Y,那么99%的时间专门化函数模板是Z。

使函数委托给实际可以以任何方式专门化的内容:

template<typename T>
struct FooImpl {
  static void func() = delete; // 删除的默认实现
                               // 需要专门化才能有效
                               // 不严格要求,但提供更多信息的错误
};

template<>
struct FooImpl<int> {
  static int func() { return 1; }
};

template<typename T>
struct FooImpl<Dummy<T>> {
  static Dummy<T> func() { return {}; }
};

template<typename T>
T foo() {
  return FooImpl<T>::func();
}
英文:

> Is there a way to get around this?

If a someone has a problem X, and the solution is Y, then 99% of the time specializing function templates is Z.

Make the function delegate to something that actually can be specialized any way you want:

template&lt;typename T&gt;
struct FooImpl {
  static void func() = delete; // Deleted default implementation
                               // Need to specialize to be valid
                               // Not strictly required, but gives
                               // more informative errors
};

template&lt;&gt;
struct FooImpl&lt;int&gt; {
  static int func() { return 1; }
};

template&lt;typename T&gt;
struct FooImpl&lt;Dummy&lt;T&gt;&gt; {
  static Dummy&lt;T&gt; func() { return {}; }
};

template&lt;typename T&gt;
T foo() {
  return FooImpl&lt;T&gt;::func();
}

huangapple
  • 本文由 发表于 2023年2月23日 22:16:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75546018.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定