C++ same function parameters with different return type

前端 未结 10 1087
猫巷女王i
猫巷女王i 2020-12-16 18:25

I need to find some way to mock an overload of a function return type in C++.

I know that there isn\'t a way to do that directly, but I\'m hoping there\'s some out-o

10条回答
  •  无人及你
    2020-12-16 19:03

    If the datastrings are compile-time constants (as said in answering my comment), you could use some template magic to do the job. An even simpler option is to not use strings at all but some data types which allow you then to overload on argument.

    struct retrieve_int {} as_int;
    struct retrieve_double {} as_double;
    
    int RetrieveValue(retrieve_int) { return 3; }
    double RetrieveValue(retrieve_double) { return 7.0; }
    
    auto x = RetrieveValue(as_int);    // x is int
    auto y = RetrieveValue(as_double); // y is double
    

提交回复
热议问题