conectionist
conectionist

Reputation: 2924

In c++, can I have a class which has some functions only under certain conditions?

I have this code:

class A
{
public:
    A(int _a, int _b = 0) : a(_a), b(_b) {}
    void f(){}
    #if _b == 0
    void g(){}
    #endif

private:
    int a;
    int b;
};

int main()
{
    A x(1);
    x.g();

    return 0;
}

I want A to have the method g() only if b is 0. I know the code above doesn't work, but I want to know if there is some way of achieving this.

Upvotes: 0

Views: 87

Answers (3)

You should use a template and provide the number of dimensions as a template argument (compile time constant). Then use specialization to provide the different interfaces:

class Matrix_base {...};     // common code
template <int Dimensions>
struct Matrix;
template <>
struct Matrix<1> : Matrix_base {
    int operator[]( std::size_t idx ) const {
       // ...
    }
};
template <>
struct Matrix<2> : Matrix_base {
    int operator()( std::size_t idx1, std::size_t idx2 ) const {
       // ...
    }
}
// ...
Matrix<1> v( 10 );
std::cout << v[5];
// v(5,1)                  // error
Matrix<2> m( 10, 20 );
// std::cout << m[5];      // error
std::cout << m(5,1);

Upvotes: 1

user1434698
user1434698

Reputation:

No, it is impossible. b is known only at runtime. I suggest to throw an exception if you call your function and bis non-zero.

void g()
{
   if(b == 0)
   {
      Exception e("error..."); // Your exception class or a std::exception class
      throw e;
   }

   // The code from here will not be executed
}

Upvotes: 0

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143229

No. The values are only known at runtime. But you can check values in function and throw a fit.

Upvotes: 2

Related Questions