tags:

views:

132

answers:

1

I have the following pattern:

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;
}

It doesn't compile, the error message is

Error C2975. error C2975: 'dom' : invalid argument template for 'MyClass'

If I replace template <int c> by template <int c, int d> and use it accordignly, it works fine. But I want d to be the same value as b.

My questions:

  1. Why the example doesn't work?
  2. How can I enforce d to be the same than b?

Thanks.

+5  A: 

The following code compiles fine for me (as it should).

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;
}

Note that in your code:

  1. You are returning a reference to a temporary.
  2. The operator * is not accessible from outside the class because it's private.

Please post real code and indicate the line casing the error.

avakar
I made some edit to make the code more accurate. Thanks for the tip about the reference.Your example compiles, mine still doesn't except if I define the body of the method inside the class (!).BTW any reasons for using the `struct` keyword instead of `class`?
gregseth
The default access mode of `struct` is `public`, thus it saves space in examples ;)
Georg Fritzsche
This code is now identical to yours, except for the `// ..do stuff..` part. Perhaps the error is there? (Using `struct` makes the member public, but apart from that is exactly the same as `class`).
Mike Seymour