如何使用可以在c ++中更改的函数创建结构?

时间:2018-01-30 09:26:40

标签: c++ struct

我想创建一个可以初始化的结构,这样不使用if或switch语句,结构就会显示用户在开头选择的函数。与C#中的readonly类似。 因此,在声明包含函数S的结构f()之后,如果我将结构声明为f()或者S("a"),那么S("b")应该不同 Use a conditional formula to dynamically change the location of a report’s image. 1. Add an image to the report: -> Insert -> Picture This image will act as a placeholder. Ensure that the placeholder is the same size as the one that will be dynamically loaded, otherwise, the image will be scaled. 2. Change the image’s Graphic Location: ->right click image ->select Format Graphic… ->select Picture tab ->click the conditional-formula button (looks like x+2) ->set the formula’s text to the name of the formula or parameter field that will contain the image’s URL ->save the formula and click the OK button ->Save the report It worked for me. Source: cogniza.com

  1. 有可能吗?
  2. 如果是,怎么样?

1 个答案:

答案 0 :(得分:4)

您可以使用function pointer或其他可调用对象。您可以将这些内容放在地图中,并在构建S

时在地图中查找
void f_A() { std::cout << "called a"; }
void f_B() { std::cout << "called b"; }

std::map<std::string, void(*)()> functions = { { "a", f_A }, { "b", f_B } };

struct S
{
    S(std::string id) : f(functions[id]) {}
    void(*f)();
}

int main()
{
    S a("a");
    S b("b");
    a.f();
    b.f();
    return 0;
}

如果您需要S拥有其他状态,并且f需要使用它,则可以修改示例:

struct S; // need to forward declare S

void f_A(S* s) { std::cout << "called a with " << s->foo; }
void f_B(S* s) { std::cout << "called b with " << 2 * s->foo; }

std::map<std::string, void(*)(S*)> functions = { { "a", f_A }, { "b", f_B } };

struct S
{
    S(std::string id, int foo_) : f_impl(functions[id]), foo(foo_) {}
    void f() { f_impl(this); }
    int foo;
private:
    void (*f_impl)(S*);
}