简体   繁体   English

专业化可变参数模板成员function

[英]Specialize variadic template member function

Is there a way to get this "fake overloading" argument specialization to work?有没有办法让这种“假重载”参数专业化工作?

#include <iostream>

class Foo
{
public:
  template < typename T, typename ... Args > 
  T* bar (Args&& ... args);
};

template <> 
int* Foo::bar()
{
  std::cout << "int* bar()\n";
  return new int;
}

// error: template-id ‘bar<>’ for ‘double* Foo::bar(double)’ does not match any template declaration
template <> 
double* Foo::bar(double d)
{
  std::cout << "double* bar(" << d << ")\n";
  return new double;
}

int main()
{
  Foo f;
  f.bar<int>();
  f.bar<double>(3.0);
}

One solution would be to actually overload the function, eg一种解决方案是实际使 function 过载,例如

class Foo
{
public:
  template < typename T, typename ... Args > 
  T* bar (Args&& ... args);
  template < typename T, typename U > 
  T* bar (U u);
};

but I would prefer to avoid that if possible.但如果可能的话,我宁愿避免这种情况。 I am looking at dozens of allowed combinations of return type and arguments, so overloading is impractical.我正在查看返回类型和 arguments 的数十种允许组合,因此重载是不切实际的。

I assume some SFINAE magic should make it possible to only enable very specific combinations of return type and arguments, but I feel that I'm probably missing a simpler option.我假设一些 SFINAE 魔法应该可以只启用返回类型和 arguments 的非常特定的组合,但我觉得我可能缺少一个更简单的选项。

The parameter type of the specialization double , doesn't match the parameter type of the primary template Args&& , as the error message said.如错误消息所述,专业化double的参数类型与主模板Args&&的参数类型不匹配。

The primary template is applying forwarding reference, which could instantiate as both lvalue-reference or rvalue-reference.主模板正在应用转发引用,它可以实例化为左值引用或右值引用。 For rvalue-reference (which matches the usage in main() ) the specialization should be对于右值引用(与main()中的用法相匹配),专业化应该是

template <> 
double* Foo::bar(double&& d)
{
  std::cout << "double* bar(" << d << ")\n";
  return new double;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM