Question

I looked into the GCC STL (4.6.1) and saw that std::copy() uses an optimized version in case the builtin __is_trivial() evaluates to true.

Since the std::copy() and std::reverse_copy() templates are very useful for copying elements in arrays, I would like to use them. However, I have some types (which are results of template instantiations) that are structs that contain some trivial values, no pointers and have no copy constructor or assignment operator.

Is G++ smart enough to figure out that my type in fact is trivial? Is there any way in C++98 to make sure an STL implementation knows that my type is trivial?

I guess that in C++11, things will become convenient using the is_trivial<> type trait. Is this right?

Thanks!

EDIT: Sorry for being so late with this, but here is an example of a pretty simple Type class that is not trivial to GCC and llvm. Any ideas?

#include <iostream>

struct Spec;

template <typename TValue, typename TSpec>
class Type
{
public:
    TValue value;

    Type() : value(0) {}
};

int main()
{
    std::cerr << "__is_trivial(...) == "
              << __is_trivial(Type<char, Spec>) << '\n';                                                                                                                                                                                                                                    
    return 0;
} 
Was it helpful?

Solution

There has been some debate over what trivial meant.

For example, your example is not trivially constructible as far as I can tell (std::is_trivially_default_constructible would return false I think).

In your case, I think you would need the new trait std::is_trivially_copyable, which is more fine grained. So... upgrade your compiler ?

OTHER TIPS

__is_trivial gives the right value for all types.

You can't rely on any paticular STL implementation to use it, although if the compiler vendor supplied it then it probably does contain various compiler-specific improvements behinds the scenes.

C++11's std::is_trivial is merely standardising this feature, there's no reason for an implementation not to use it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top