What is the best way to express a template literal?

I have a function that can be reduced to something like this:

template<class T>
T foo(T x)
{
  return 123.45 / x;
}

I would like to make sure that the numeric literal 123.45 is the same type as x. Let's say that T can be any number type: signed / unsigned char long or floating for a long double.

What is the most modern way to indicate that 123.45 should be of type T?

My requirements

  • Warnings should not be issued (each time each warning is turned on).
  • I want the decimal number 123.45 to have T precision when used in the calculation.
  • I want the most elegant solution that achieves these goals.

Questions to be addressed

  • "Casting in the old style", i.e. (T)123.45, essentially not recommended in C ++.
  • static_cast<T>(123.45) . , , , .
  • , (, 123.45L), , T long double, .

5-7-2014

T(123.45), , , . , long double(123.45), ++ . static_cast<long double>(123.45).

+3
5

template<class T>
T foo(T x)
{
  return T(123.45) / x;
}

.

+2

static_cast - . , C cast , , , .

, static_cast , explicit.

, T{ 123.45 }. C-, direct-list-initialization. - explicit, . ( . , . GCC , 12.0 int; , .)

+2

. , , , :-) C-, (a) , (b) . .

L, , T , double. static_cast<long double>(123.45) != 123.45L.

, T , mpf_class GMP , , long double. , boost::lexical_cast<T>("123.45"). , , enable_if - .

, T , int, , , short(123.45) / x int(123.45) / x, int short(123.45) == int(123.45), T , int, , , long(123.45) / x , int(123.45) / x, T int(123.45) == long(123.45). , 123 [*]. 123.45 T, . -1 / (unsigned char)2 != (unsigned char)-1 / (unsigned char)2.

[*] bool, , .

+2
source

You can also try to do this as follows:

// RealConstant.h

template <typename Real>
class RealConstant
{
public:

    static 
    const Real value;

};

#define REAL_CONSTANT_DECLARATION(Real) \
template <> \
const Real RealConstant<Real>::value;

REAL_CONSTANT_DECLARATION(float)
REAL_CONSTANT_DECLARATION(double)
REAL_CONSTANT_DECLARATION(long double)

#undef REAL_CONSTANT_DECLARATION


// RealConstant.cpp

#include "RealConstant.h"

#define REAL_CONSTANT_DEFINITION(Real, constantValue) \
template <> \
const Real RealConstant<Real>::value = constantValue;

REAL_CONSTANT_DEFINITION(float, 123.45f)
REAL_CONSTANT_DEFINITION(double, 123.45)
REAL_CONSTANT_DEFINITION(long double, 123.45L)

#undef REAL_CONSTANT_DEFINTION


// File in which `foo` function template is defined

#include "RealConstant.h"

template<class T>
T foo(T x)
{
    return RealConstant<T>::value / x;
}

Macros are really not needed, of course.

+1
source

I would initialize a constant Tfrom a literal:

template<class T>
T foo(T x)
{
  const T magic = 123.45;
  return magic / x;
}

it is both more explicit and readable than static_cast, and, more importantly, it gives you the opportunity to document a magic number with your own name;)

0
source

Source: https://habr.com/ru/post/1611834/


All Articles