Neal
Neal

Reputation: 942

How to set up static const variables inside templated classes?

I have the following code:

template<typename flow_t, typename cost_t>
struct min_cost_flow {
    static const flow_t FLOW_INF = numeric_limits<flow_t>::max() / 2;
    static const cost_t COST_INF = numeric_limits<cost_t>::max() / 2;
    ...
};

Unfortunately it does not compile and gives the error "[...] undefined reference to `min_cost_flow::COST_INF".

Two fixes I've tried that I don't like include changing const to constexpr (successfully compiles on my machine, but not on another with an older version of gcc), and defining the value of the constants below the class, but this separates the values too far from where I want to use them. Any other ideas?

Upvotes: 0

Views: 45

Answers (1)

John Zwinck
John Zwinck

Reputation: 249642

Just turn them into member functions instead:

template<typename flow_t, typename cost_t>
struct min_cost_flow {
    static const flow_t FLOW_INF() { return numeric_limits<flow_t>::max() / 2; }
    static const cost_t COST_INF() { return numeric_limits<cost_t>::max() / 2; }
};

If your compiler doesn't support C++11, use const instead of constexpr.

Upvotes: 1

Related Questions