Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imbricated C++ template

Tags:

c++

templates

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.

like image 528
gregseth Avatar asked Nov 21 '25 05:11

gregseth


1 Answers

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.

like image 200
avakar Avatar answered Nov 23 '25 19:11

avakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!