0

我有这个代码:

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

我希望 A 只有当 b 为 0 时才具有 g() 方法。我知道上面的代码不起作用,但我想知道是否有某种方法可以实现这一点。

4

3 回答 3

2

不,这些值仅在运行时已知。但是您可以检查函数中的值并进行拟合。

于 2012-09-14T18:38:05.720 回答
1

您应该使用模板并提供维数作为模板参数(编译时间常数)。然后使用特化来提供不同的接口:

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);
于 2012-09-14T18:55:08.243 回答
0

不,这是不可能的。b只有在运行时才知道。b如果你调用你的函数并且非零,我建议抛出一个异常。

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
}
于 2012-09-14T18:44:14.340 回答