C++14 Variable Templates: what is their purpose? Any usage example?

前端 未结 6 1736
死守一世寂寞
死守一世寂寞 2020-11-29 00:52

C++14 will allow the creation of variables that are templated. The usual example is a variable \'pi\' that can be read to get the value of the mathematical constant π for va

6条回答
  •  [愿得一人]
    2020-11-29 01:08

    I wonder whether something along these lines would be possible: (assuming availability of template lambdas)

    void some_func() {
        template
        std::map storage;
    
        auto store = [](int key, const T& value) { storage[key] = value; };
    
        store(0, 2);
        store(1, "Hello"s);
        store(2, 0.7);
    
        // All three values are stored in a different map, according to their type. 
    }
    

    Now, is this useful?

    As a simpler use, notice that the initialization of pi uses explicit conversion (explicit call of a unary constructor) and not uniform initialization. Which means that, given a type radians with a constructor radians(double), you can write pi.

提交回复
热议问题