有条件地为类赋值

时间:2013-03-11 18:42:18

标签: c++ class object cuda

如果我有两个班级:

class A{
    f();
}

class B{
    f();
};

我需要根据以下条件将这些类中的一个分配给对象:

define variable
if condition1
    variable = A
else
    variable = B

然后我会使用指定的variable.f();

3 个答案:

答案 0 :(得分:1)

如果AB是不相关的类型(即不是继承层次结构的一部分),您可以将Boost.Variant与boost::static_visitor<>类结合使用来实现某些目的类似:

#include <boost/variant.hpp>
#include <iostream>

struct A { void f() { std::cout << "A::f();" << std::endl; } };
struct B { void f() { std::cout << "B::f();" << std::endl; } };

struct f_caller : boost::static_visitor<void>
{
    template<typename T>
    void operator () (T& t)
    {
        t.f();
    }
};

bool evaluate_condition()
{
    // Just an example, some meaningful computation should go here...
    return true;
}

int main()
{
    boost::variant<A, B> v;
    if (evaluate_condition())
    {
        A a;
        v = a;
    }
    else
    {
        B b;
        v = b;
    }

    f_caller fc;
    v.apply_visitor(fc);
}

答案 1 :(得分:1)

您应该关注继承和虚函数。 代码可能看起来像

class Base
{
    virtual void f() = 0;
};

class A : public Base
{
    virtual void f()
    {
        //class A realization of f
    }
};

class B : public Base
{
    virtual void f()
    {
        //class B realization of f
    }
};

然后你可以这样做

Base* VARIABLE = 0;
if (*condition*)
{
   VARIABLE = new A();
}
else
{
   VARIABLE = new B();
}

VARIABLE->f();

但使用继承和虚函数并不总是一个好主意。你的A和B类应该有一些共同点,至少是函数f()的含义。

答案 2 :(得分:0)

您所做的事情在设计模式中被称为“工厂模式”。以上答案涵盖了如何实施。您可以在How to implement the factory method pattern in C++ correctly和wiki(http://en.wikipedia.org/wiki/Factory_method_pattern)获取更多信息。

相关问题