If there is any statement you would get rid of in C++ waht would it be?

Pages: 12
You could, but if the function's purpose is to swap two elements, why not just call it swap (one name, one meaning)?
I could have called it swap(), since std::swap() is where it belongs, I just wanted to highlight the fact that it's a different function, I guess.
Why not call my_sort() sort(), for that matter?

But passing via function pointer penalizes the user since the optimizer will not be able to inline the function calls, so I would avoid passing by pointer.
It's just an example. You could pass a functor or, if you like verbosity, a template parameter.

It's a problem with template specialization in general. How can you be sure that the compiler invokes your specialization vs. the default templated version?
I don't think I'm following. Could you give an example?
I would have, but my sort() template function would have been ambiguous with std::sort() then.

Really hypothetical example:

1
2
3
4
5
6
7
8
9
10
11
struct frobnicate : boost::static_visitor<>
{
    template< typename T >
    void operator()( const T& t ) const
        { std::cout << t << << std::endl; }   // As an example
};

// ...
typedef boost::variant< int, char, double, std::string > MyVariant;
MyVariant v( std::string( "Hello World" ) );
boost::apply_visitor( frobnicate(), v );


Suppose that I just added the std::string element to MyVariant, and I know that frobnicate
needs a specialization of operator() to handle std::string. Problem is, if I forget to add it,
the code still compiles; it just calls the templated operator() which is not what I want. I'd
like it to not compile, but the only way to do that is to eliminate the templated operator()
and write the same function three times for int, char, and double, which seems stupid
(after all, that's part of what templates are for).

In my example, the templated operator() is like std::swap().

Now this example isn't quite the same as the issue you brought up, I realize, because in my
case "std::swap<T>()" and "std::swap<std::string>()" are declared at the same point, so you
either get both or neither. The problem you raise is just another example of code that is
structured such that it is possible to have unintended or unexpected behavior. But that's
basically unavoidable in any non-trivial application.
Topic archived. No new replies allowed.
Pages: 12