Parameterized variable type in function (c++) -
I am trying to write something with the following lines:
Lt; T & gt; (Four * Environment, T & amp; D, T Default Value) {bool ret = false; // Try to get environment Varianable ret = handle.getParam (Environmental environment, data); If (! Ret) {data = defaultValue}} int main () {int valOne; Float valtao; // Find the value of type int set data ("some_int_value", valOne, 10); // 10 the default value is the value of // type float set data ("some_float_value", valTwo, 0.05f); // 0.05 is the default value} One way to do this should be va_list is there a way that I can complete with orbit?
Thank you
I think you were almost there: < Pre> template & lt; Typename T & gt; Zero SetData (Four * Environment Variable, T & amp; D, Data Default, T) {// ...} It should do whatever you want. Note, however, that the same T is used for the previous two arguments, so this function calls T : setdata (" Some_float_value ", valTwo, 0.05); Because 0.05 is a double , while valTwo is a float. During typewriter, a similar conversion will not be made, because the compiler is trying to match exact types. Although it is easy to fix:
setdata ("some_float_value", valtavo, 0.05f); // ^ f suffix is the last logic type of a private float , so that T Code> float .
Probably, you can give different types of permissions for the second and third arguments, until the third one is converted into one. In this case, you can change your function template as follows You can define:
template & lt; Typename t, typename u & gt; Zero setdata (four * environmental variable, T & amp; data, U default value) {// ...} However, note that this will allow you to instantiate setData With the help of any two types T and you , you probably want your template to be only U s that are convertible to T s Some SFINE move will work with the std :: is_convertible type attribute: #include & lt; Type_traits & gt; Template & lt; Typename T, typename u, typewriter std :: enable_if & lt; Std :: is_convertible & lt; U, T & gt; :: value & gt; :: type * = nullptr & gt; Zero SetData (Four * Environment Variable, T & amp; D, Data, U Default Value) {// ...} Now you can also use your original call without compiler errors Are:
setdata ("some_float_value", valTwo, 0.05); // ^^^^
Comments
Post a Comment