Imbricated C++模板

gre*_*eth 3 c++ templates

我有以下模式:

template <int a, int b>
class MyClass
{
public:
  template <int c>
  MyClass<a, c> operator*(MyClass<b, c> const &other) const;
};

// ../..

template <int a, int b> template <int c>
MyClass<a, c> MyClass<a, b>::operator*(MyClass<b, c> const &other) const //< error here
{
  MyClass<a, c> result;
  // ..do stuff..
  return result;
}
Run Code Online (Sandbox Code Playgroud)

它不编译,错误信息是

错误C2975.错误C2975:'dom':'MyClass'的参数模板无效

如果我更换template <int c>由template <int c, int d>并且accordignly使用它,它工作正常.但我希望d成为同样的价值b.

我的问题:

  1. 为什么这个例子不起作用?
  2. 我怎么能强制执行d相同的b?

谢谢.

ava*_*kar 5

以下代码为我编译好(应该如此).

template <int a, int b>
struct MyClass
{
    template <int c>
    MyClass<a, c> operator*(MyClass<c, b> const &other) const;
};

template <int a, int b> template <int c>
MyClass<a, c> MyClass<a, b>::operator*(MyClass<c, b> const &other) const
{
    MyClass<a, c> result;
    return result;
}

int main()
{
    MyClass<1, 2> a;
    MyClass<3, 2> b;
    a * b;
}
Run Code Online (Sandbox Code Playgroud)

请注意,在您的代码中:

  1. 您正在返回对临时的引用.
  2. 在operator *不能从外部类,因为它是私有的访问.

请发布实际代码并指出错误的行.