Teuchos - Trilinos Tools Package  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Modules | Classes | Macros | Functions
Teuchos Language Support Utilities

Modules

 Template classes for testing assertions at compile time.
 
 Utility code for throwing exceptions and setting breakpoints.
 

Classes

class  Teuchos::m_bad_cast
 Exception class for bad cast. More...
 
class  Teuchos::ToStringTraits< T >
 Default traits class for converting objects into strings. More...
 
class  Teuchos::TypeNameTraits< T >
 Default traits class that just returns typeid(T).name(). More...
 
class  Teuchos::ValueTypeConversionTraits< TypeTo, TypeFrom >
 Default traits class for all conversions between value types. More...
 
class  Teuchos::asFunc< TypeTo >
 Function object wrapper for as(). More...
 

Macros

#define TEUCHOS_UNREACHABLE_RETURN(dummyReturnVal)   TEUCHOS_UNREACHABLE_RETURN_IMPL(dummyReturnVal)
 Avoid warning about unreachable or missing return from function. More...
 
#define TEUCHOS_SWITCH_DEFAULT_DEBUG_ASSERT()
 Macro to insert switch default that throws in a debug build. More...
 
#define TEUCHOS_IF_ELSE_DEBUG_ASSERT()   else {}
 Macro to insert else block that throws in a debug build. More...
 
#define TEUCHOS_STANDARD_CATCH_STATEMENTS(VERBOSE, ERR_STREAM, SUCCESS_FLAG)   TEUCHOS_STANDARD_CATCH_STATEMENTS_IMPL(VERBOSE, ERR_STREAM, true, SUCCESS_FLAG)
 Simple macro that catches and reports standard exceptions and other exceptions. More...
 

Functions

template<class TypeTo , class TypeFrom >
TypeTo Teuchos::as (const TypeFrom &t)
 Convert from one value type to another. More...
 
template<class TypeTo , class TypeFrom >
TypeTo Teuchos::asSafe (const TypeFrom &t)
 Convert from one value type to another, with validity checks if appropriate. More...
 
template<class T_To , class T_From >
T_To & Teuchos::dyn_cast (T_From &from)
 Dynamic casting utility function meant to replace dynamic_cast<T&> by throwing a better documented error message. More...
 
template<class T >
const T & Teuchos::getConst (T &t)
 Return a constant reference to an object given a non-const reference. More...
 
template<class TypeTo , class TypeFrom >
TypeTo Teuchos::implicit_cast (const TypeFrom &t)
 Perform an implicit cast of concrete types with the casted object returned by value. More...
 
template<class TypeTo , class TypeFrom >
TypeTo & Teuchos::implicit_ref_cast (TypeFrom &t)
 Perform an implicit cast of reference types with a reference being returned. More...
 
template<class TypeTo , class TypeFrom >
TypeTo * Teuchos::implicit_ptr_cast (TypeFrom *t)
 Perform an implicit cast of pointer types with a pointer being returned. More...
 
template<typename T >
std::string Teuchos::toString (const T &t)
 Utility function for returning a pretty string representation of a object of type T. More...
 
TEUCHOSCORE_LIB_DLL_EXPORT
std::string 
Teuchos::demangleName (const std::string &mangledName)
 Demangle a C++ name if valid. More...
 
template<typename T >
std::string Teuchos::typeName (const T &t)
 Template function for returning the concrete type name of a passed-in object. More...
 
template<typename T >
std::string Teuchos::concreteTypeName (const T &t)
 Template function for returning the type name of the actual concrete name of a passed-in object. More...
 

Detailed Description

Macro Definition Documentation

#define TEUCHOS_UNREACHABLE_RETURN (   dummyReturnVal)    TEUCHOS_UNREACHABLE_RETURN_IMPL(dummyReturnVal)

Avoid warning about unreachable or missing return from function.

Consider a function like:

int func(const ESomeEnum val)
{
switch (val) {
case VAL1: return 1;
case VAL2: return 2;
default: TEUCHOS_TEST_FOR_EXCEPT(true);
}
}

That code will never execute out of the switch statement. However, some compilers will provide a warning that the function may not return a value. Therefore, one can remove this warning by adding a dummy return value like:

int func(const ESomeEnum val)
{
switch (val) {
case VAL1: return 1;
case VAL2: return 2;
default: TEUCHOS_TEST_FOR_EXCEPT(true);
}
return -1; // Will never get called!
}

That removes the "may not return value" warning on those compilers. But other compilers will correctly warn that return -1; will never be executed with a warning like "statement is unreachable". Therefore, to address warnings like this, this macro is used like:

int func(const ESomeEnum val)
{
switch (val) {
case VAL1: return 1;
case VAL2: return 2;
default: TEUCHOS_TEST_FOR_EXCEPT(true);
}
}

On compilers that warn about the return being unreachable the return statement is skipped. On every other compiler, the return statement is kept which results in safer code under refactoring (by avoiding undefined behavior when returning from a function by fall-through without returning an explicit value.

Definition at line 131 of file Teuchos_CompilerCodeTweakMacros.hpp.

#define TEUCHOS_SWITCH_DEFAULT_DEBUG_ASSERT ( )

Macro to insert switch default that throws in a debug build.

In a non-debug build, however, this does nothing. This is also helpful for removing code that would otherwise show as not being covered.

Definition at line 59 of file Teuchos_DebugDefaultAsserts.hpp.

#define TEUCHOS_IF_ELSE_DEBUG_ASSERT ( )    else {}

Macro to insert else block that throws in a debug build.

In a non-debug build, however, this does nothing. This is also helpful for removing code that would otherwise show as not being covered.

Definition at line 83 of file Teuchos_DebugDefaultAsserts.hpp.

#define TEUCHOS_STANDARD_CATCH_STATEMENTS (   VERBOSE,
  ERR_STREAM,
  SUCCESS_FLAG 
)    TEUCHOS_STANDARD_CATCH_STATEMENTS_IMPL(VERBOSE, ERR_STREAM, true, SUCCESS_FLAG)

Simple macro that catches and reports standard exceptions and other exceptions.

This macro should be used to write simple main() program functions wrapped in a try statement as:

int main(...)
{
bool verbose = true;
bool success = true;
try {
...
}
TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);
return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
}

NOTE: This macro will print out stacktraces generated by exceptions thrown with the TEUCHOS_TEST_FOR_EXCEPTION() family of macros (see the main doc page for details).

Examples:
ArrayRCP_test.cpp, CommandLineProcessor/cxx_main.cpp, FancyOutputting_test.cpp, ParameterList/cxx_main.cpp, and test/MemoryManagement/RCP_test.cpp.

Definition at line 136 of file Teuchos_StandardCatchMacros.hpp.

Function Documentation

template<class TypeTo , class TypeFrom >
TypeTo Teuchos::as ( const TypeFrom &  t)
inline

Convert from one value type to another.

Template Parameters
TypeToThe type to which to convert; the output type.
TypeFromThe type from which to convert; the input type.

User documentation

This template function lets you convert from one value type to another, possibly with checks for overflow (where appropriate) in a debug build of Teuchos. For example, to convert between int and double:

double d = 3.14;
int i = Teuchos::as<double> (d);
assert (i == 3);

In a debug build of Teuchos, this will check for overflow, since there are some double-precision floating-point values that do not fit in a 32-bit integer. In a release build, this will not check for overflow. You are responsible for knowing the difference. If you always want to check for overflow (e.g., to validate user input), use the asSafe() function. Note that conversion from a floating-point number to an integer, or from a higher-precision floating-point number to a lower-precision floating-point number, may truncate or round (as it does in the above example). We do not check for truncation or rounding.

"Debug build of Teuchos" means more than just building with debug compiler flags. It means debug checking was turned on when Trilinos was built. If you are building Trilinos yourself, you may turn on debug checking by setting the Trilinos_ENABLE_DEBUG CMake configure option to ON (rather than OFF, which is the default). Note that enabling debug checking affects other operations in Teuchos besides this conversion, and may have a significant run-time cost, especially for RCP and ArrayRCP.

The IEEE 754 standard defines the result of conversions from a larger to a smaller built-in floating-point type, including double to float, long double to float, and long double to double. Such conversions might overflow (result in a value too large in magnitude to fit in the target type) or underflow (result in a value too small to fit in a normalized value of the target type). We never check for overflow or underflow for these conversions. Their behavior depends on the current rounding mode and whether your hardware and compiler correctly implement denormalized values. Typically, overflow results in an Inf of the same sign as the input, and underflow results in either a denormalized value or zero. If you want to do bounds checking, you should set the appropriate trap so that overflow or underflow will raise the SIGFPE signal. Please refer to the IEEE 754 standard for details. Note that debug-mode as() conversions from e.g., std::string to built-in floating-point types still check for overflow.

Note
We cannot promise that converting from a type T1 to another type T2 and back again will result in the same T1 value with which we started. For example, converting from a long long to a double may result in truncation, since long long has 63 bits of significand and double has 53.

Developer documentation

This function uses the traits class ValueTypeConversionTraits to perform checking and conversion. If debug checking is turned on, this function uses the traits class' safeConvert() method to perform possibly checked conversion. Otherwise, it uses the traits class' convert() method for unchecked conversion.

If you want to specialize this function's behavior, you should specialize ValueTypeConversionTraits for your combination of input and output types (TypeFrom resp. TypeTo). Be sure to define the specialization in the Teuchos namespace. We provide specializations of ValueTypeConversionTraits in this file for a variety of types. You must define both safeConvert() and convert() in the specialization, since as() will call safeConvert() in a debug build and convert() in a release build.

Note
The implementations below do not consider truncation of floating-point values to be unsafe conversion. For example, converting from a long long (63 bits of significand) to a double (53 bits of significand) may result in truncation, but we do not consider this unsafe. "Unsafe" mainly refers to overflow or lack of representation.
Examples:
ArrayRCP_test.cpp, and ParameterList/cxx_main.cpp.

Definition at line 2840 of file Teuchos_as.hpp.

template<class TypeTo , class TypeFrom >
TypeTo Teuchos::asSafe ( const TypeFrom &  t)
inline

Convert from one value type to another, with validity checks if appropriate.

Template Parameters
TypeToThe type to which to convert; the output type.
TypeFromThe type from which to convert; the input type.

User documentation

This template function lets you convert from one value type to another. For example, to convert between int and double:

double d = 3.14;
int i = Teuchos::asSafe<double> (d);
assert (i == 3);

This function always checks for validity of the conversion before attempting it. Examples of invalid conversions are those which would overflow, for example from double to int, if the double-precision floating-point input is bigger than the largest int or smaller than the smallest int. If you only which to check in a debug build, use the as() function instead. Note that conversion from a floating-point number to an integer, or from a higher-precision floating-point number to a lower-precision floating-point number, may truncate or round (as it does in the above example).

The IEEE 754 standard defines the result of conversions from a larger to a smaller built-in floating-point type, including double to float, long double to float, and long double to double. Such conversions might overflow (result in a value too large in magnitude to fit in the target type) or underflow (result in a value too small to fit in a normalized value of the target type). We never check for overflow or underflow for these conversions. Their behavior depends on the current rounding mode and whether your hardware and compiler correctly implement denormalized values. Typically, overflow results in an Inf of the same sign as the input, and underflow results in either a denormalized value or zero. If you want to do bounds checking, you should set the appropriate trap so that overflow or underflow will raise the SIGFPE signal. Please refer to the IEEE 754 standard for details. Note that asSafe() conversions from e.g., std::string to built-in floating-point types still check for overflow.

Developer documentation

This function uses the traits class ValueTypeConversionTraits to perform the actual checking and conversion. It always uses the traits class' safeConvert() method to perform a possibly checked conversion.

If you want to specialize this function's behavior, you should specialize ValueTypeConversionTraits for your combination of input and output types (TypeFrom resp. TypeTo). Be sure to define the specialization in the Teuchos namespace. We provide specializations of ValueTypeConversionTraits for a variety of types.

Note
The implementations below do not consider truncation of floating-point values to be unsafe conversion. For example, converting from a long long (63 bits of significand) to a double (53 bits of significand) may result in truncation, but we do not consider this unsafe. "Unsafe" mainly refers to overflow or lack of representation.

Definition at line 2850 of file Teuchos_as.hpp.

template<class T_To , class T_From >
T_To& Teuchos::dyn_cast ( T_From &  from)
inline

Dynamic casting utility function meant to replace dynamic_cast<T&> by throwing a better documented error message.

Existing uses of the built-in dynamic_cast<T&>() operator such as:

C &c = dynamic_cast<C&>(a);

are easily replaced as:

C &c = dyn_cast<C>(a);

and that is it. One could write a perl script to do this automatically.

This utility function is designed to cast an object reference of type T_From to type T_To and if the cast fails at runtime then an std::exception (derived from std::bad_cast) is thrown that contains a very good error message.

Consider the following class hierarchy:

class A {};
class B : public A {};
class C : public A {};

Now consider the following program:

int main( int argc, char* argv[] ) {
B b;
A &a = b;
try {
std::cout << "\nTrying: dynamic_cast<C&>(a);\n";
dynamic_cast<C&>(a);
}
catch( const std::bad_cast &e ) {
std::cout << "\nCaught std::bad_cast std::exception e where e.what() = \"" << e.what() << "\"\n";
}
try {
std::cout << "\nTrying: Teuchos::dyn_cast<C>(a);\n";
}
catch( const std::bad_cast &e ) {
std::cout << "\nCaught std::bad_cast std::exception e where e.what() = \"" << e.what() << "\"\n";
}
return 0;
}

The above program will print something that looks like (compiled with g++ for example):

 Trying: dynamic_cast<C&>(a);

 Caught std::bad_cast std::exception e where e.what() = "St8bad_cast"

 Trying: Teuchos::dyn_cast<C>(a);

 Caught std::bad_cast std::exception e where e.what() = "../../../../packages/teuchos/src/Teuchos_dyn_cast.cpp:46: true:
 dyn_cast<1C>(1A) : Error, the object with the concrete type '1B' (passed in through the interface type '1A')  does
 not support the interface '1C' and the dynamic cast failed!"

The above program shows that the standard implementation of dynamic_cast<T&>() does not return any useful debugging information at all but the templated function Teuchos::dyn_cast<T>() returns all kinds of useful information. The generated error message gives the type of the interface that the object was passed in as (i.e. A), what the actual concrete type of the object is (i.e. B) and what type is trying to be dynamically casted to (i.e. C). This type of information is extremely valuable when trying to track down these type of runtime dynamic casting errors. In some cases (such as with gdb), debuggers do not even give the type of concrete object so this function is very important on these platforms. In many cases, a debugger does not even need to be opened to diagnose what the problem is and how to fix it.

Note that this function is inlined and does not incur any significant runtime performance penalty over the raw dynamic_cast<T&>() operator.

Examples:
FancyOutputting_test.cpp.

Definition at line 173 of file Teuchos_dyn_cast.hpp.

template<class T >
const T& Teuchos::getConst ( T &  t)
inline

Return a constant reference to an object given a non-const reference.

Template Parameters
TThe type (without const qualifier) to make const.

This template function provides a shorthand for

const_cast<const T&>(t) 

as

getConst(t) 

This saves you the trouble of typing the name of the class, and also saves readers of your code from looking at the (possibly long) class name.

Here is an example showing why you might want to use this function.

// A class with a very long name.
class MyVeryLongClassNameWhichIsIndeedQuiteLongIsItNot { ... };
// A function which takes a const reference to an instance of that class.
void f1 (const MyVeryLongClassNameWhichIsIndeedQuiteLongIsItNot& x)
// A function which takes a nonconst reference to an instance of that class,
// but needs to call f1, which takes a const reference.
void f2 (MyVeryLongClassNameWhichIsIndeedQuiteLongIsItNot& x) {
// ... do some stuff with x ...
// Call f1. Notice how few characters this takes,
// compared with a const_cast.
f1 (getConst (x));
// ... do other stuff ...
}
Examples:
test/MemoryManagement/RCP_test.cpp.

Definition at line 82 of file Teuchos_getConst.hpp.

template<class TypeTo , class TypeFrom >
TypeTo Teuchos::implicit_cast ( const TypeFrom &  t)
inline

Perform an implicit cast of concrete types with the casted object returned by value.

This function is used as:

TypeTo myCast( const TypeFrom& a )
{
return Teuchos::implicit_cast<TypeTo>(a);
}

This function will only compile for types where an implicit conversion from objects of type TypeFrom to type TypeTo exists. Note that this is a weaker operation than a static_cast<TypeTo>(t) in that the static cast will actually compile in cases where the implicit conversion would not compile and may result in incorrect code. This function can not result in incorrect code, assuming that the implicit conversions themselves do no result in incorrect code (which is another matter all together).

This function is especially helpful when one needs to be careful of what specific type is passed in as a formal argument to a function and in comparing values. In particular, using this function is far safer than using TypeTo(t) in cases where TypeTo is a built in type since TypeTo(t) in these cases is equivalent to (TypeTo)t which is an unchecked sledge-hammer cast of the worst kind.

Definition at line 81 of file Teuchos_implicit_cast.hpp.

template<class TypeTo , class TypeFrom >
TypeTo& Teuchos::implicit_ref_cast ( TypeFrom &  t)
inline

Perform an implicit cast of reference types with a reference being returned.

This function is used as:

TypeTo& myPtrCast( TypeFrom &ref1 )
{
return Teuchos::implicit_ref_cast<TypeTo>(ref1);
}

This function will only compile for types where an implicit conversion from references of type TypeFrom& to references of TypeTo& exists. It is allowed for the type TypeFrom and TypeTo to actually be const types. For example, we can have TypeFrom = const std::iostream and TypeTo = const std::ostream and Teuchos::implicit_ref_cast<const std::ostream>(Teuchos::getConst(std::cout)) would compile just fine.

Note that this is a weaker operation than a static_cast<TypeTo&>(t) in that the static cast will actually compile in cases where the implicit conversion would not compile and may result in incorrect code. For example, a static cast from a base to a derived class will compile (and may be wrong) while this implicit cast function will not compile for casts from base to derived classes. This function can not result in incorrect code, assuming that the implicit conversions themselves do no result in incorrect code (which is another matter all together).

Definition at line 116 of file Teuchos_implicit_cast.hpp.

template<class TypeTo , class TypeFrom >
TypeTo* Teuchos::implicit_ptr_cast ( TypeFrom *  t)
inline

Perform an implicit cast of pointer types with a pointer being returned.

This function is used as:

TypeTo* myPtrCast( TypeFrom *ptr1 )
{
return Teuchos::implicit_ptr_cast<TypeTo>(ptr1);
}

This function will only compile for types where an implicit conversion from pointers of type TypeFrom* to pointers of type TypeTo* exists. It is allowed for the type TypeFrom and TypeTo to actually be const types. For example, we can have TypeFrom = const std::iostream and TypeTo = const std::ostream and Teuchos::implicit_ptr_cast<const std::ostream>(&Teuchos::getConst(std::cout)) would compile just fine.

Note that this is a weaker operation than a static_cast<TypeTo*>(t) in that the static cast will actually compile in cases where the implicit conversion would not compile and may result in incorrect code. For example, a static cast up from a base class to a derived class will compile (and may be wrong) while this implicit cast function will not compile for such casts. This function can not result in incorrect code, assuming that the implicit conversions themselves do no result in incorrect code (which is another matter all together).

Definition at line 150 of file Teuchos_implicit_cast.hpp.

template<typename T >
std::string Teuchos::toString ( const T &  t)
inline

Utility function for returning a pretty string representation of a object of type T.

NOTE: This helper function simply returns ToStringTraits<T>::toString(t) and the right way to speicalize the behavior is to specialize ToStringTraits.

Definition at line 82 of file Teuchos_toString.hpp.

std::string Teuchos::demangleName ( const std::string &  mangledName)

Demangle a C++ name if valid.

The name must have come from typeid(...).name() in order to be valid name to pass to this function.

Definition at line 53 of file Teuchos_TypeNameTraits.cpp.

template<typename T >
std::string Teuchos::typeName ( const T &  t)

Template function for returning the concrete type name of a passed-in object.

Uses the traits class TypeNameTraits so the behavior of this function can be specialized in every possible way. The default return value is typically derived from typeid(t).name().

Definition at line 115 of file Teuchos_TypeNameTraits.hpp.

template<typename T >
std::string Teuchos::concreteTypeName ( const T &  t)

Template function for returning the type name of the actual concrete name of a passed-in object.

Uses the traits class TypeNameTraits so the behavior of this function can be specialized in every possible way.

Definition at line 138 of file Teuchos_TypeNameTraits.hpp.