Kurt
Kurt

Reputation: 297

Template parameter based on expected return type

Right now I have something like this:

int a = getVal<int>("key1");
double b = getVal<double>("key2");

where getVal() just casts and returns the value corresponding to the key. Is it possible to turn that into this:

int a = getVal("key1");
double b = getVal("key2");

It's not a huge difference in code, but I'm mostly just wondering if this is possible. Thanks for the help.

Upvotes: 0

Views: 150

Answers (1)

Igor Tandetnik
Igor Tandetnik

Reputation: 52621

Something like this:

template <typename T>
T getVal(const string& key);  // as before

class ValProxy {
private:
  ValProxy(const string& key) : key_(key) {}
  string key_;

  friend ValProxy getVal(const string& key);
public:
  template <typename T>
  operator T() const {
    return getVal<T>(key_);
  }
};

ValProxy getVal(const string& key) {
  return ValProxy(key);
}

Upvotes: 4

Related Questions