0

Consider this example:

template<typename T> auto f(T u, T v = T()) { return v; }
int main() {
    double a; float b; int c; long d;   // all possible numerical types here
    auto res1 = f(a);   // is res1 == 0.0?
    auto res2 = f(b);   // is res2 == 0.0?
    auto res3 = f(c);   // is res3 == 0?
    auto res4 = f(d);   // is res4 == 0?
}

Is there a guarantee from the Standard that T() will default construct a zero numerical value whenever T is a numerical type? If not, how can I make sure that if T is numerical, then the default argument for 'v' is v = 0, and if T is not numerical, then v = T()?

a06e
  • 18,594
  • 33
  • 93
  • 169
  • 3
    Yes, it is guaranteed. See http://stackoverflow.com/questions/1613341/what-do-the-following-phrases-mean-in-c-zero-default-and-value-initializat – juanchopanza Aug 16 '15 at 22:18
  • @juanchopanza And what if I do `T v;` instead of `auto v = T()`? Will it still be zero if `T` is numeric? – a06e Aug 17 '15 at 12:39
  • @juanchopanza I read the question you linked, and follow-up links, but they don't mention templates or function arguments, so I am not sure how the rules apply here. You say it is guaranteed that `v` will be zero. Can you explain why? Maybe write an answer? Thanks in advance. – a06e Aug 17 '15 at 14:20
  • It is *value initialization*. See http://en.cppreference.com/w/cpp/language/value_initialization – juanchopanza Aug 17 '15 at 14:46

0 Answers0