C++0x -- fun(Args&...) and fun(Args const&...)

E

er

Hello, I'm hoping someone could explain the part next to the comment
"How so?!" below. Thanks.

#include <iostream>

template<typename...Args> void f(Args&...){}

template<typename U, typename...Args>
void f(U& u, Args&... args){
std::cout << "lvalue, ";
f(args...);
}

template<typename U, typename...Args>
void f(U const& u, Args&... args){
std::cout << "clvalue, ";
f(args...);
}

template<typename...Args>
void g(Args&...args)
{
f(args...);
}

template<typename...Args>
void h(Args const&...args)
{
f(args...);
}

int main()
{

int a = 1;
int const b = 2;
{
g(a, a); std::cout << std::endl;
// lvalue, lvalue // OK
}
{
g(a, b);
std::cout << std::endl;
// lvalue, lvalue // How so?!
}
{
h(a, a);
std::cout << std::endl;
// clvalue, clvalue // OK
}

return 0;

}
 
S

SG

Hello, I'm hoping someone could explain the part next to the comment
"How so?!" below. Thanks.

#include <iostream>

template<typename...Args> void f(Args&...){}

This ought to be just a simple non-template:

inline void f() {}

template<typename U, typename...Args>
void f(U& u, Args&... args){
    std::cout << "lvalue, ";
    f(args...);
}

template<typename U, typename...Args>
void f(U const& u, Args&... args){
    std::cout << "clvalue, ";
    f(args...);
}

template<typename...Args>
void g(Args&...args)
{
    f(args...);
}

template<typename...Args>
void h(Args const&...args)
{
    f(args...);
}

int main()
{
    int a = 1;
    int const b = 2;
    g(a, a); std::cout << std::endl;
    // lvalue, lvalue // OK

    g(a, b); std::cout << std::endl;
    // lvalue, lvalue // How so?!

Name lookup. You expect the first function template f to use the
second one. But this is not what's happening. If you declare the
second function template before the first one it'll work as expected:

template<typename U, typename...Args>
void f(U const& u, Args&... args);

template<typename U, typename...Args>
void f(U& u, Args&... args){
std::cout << "lvalue, ";
f(args...);
}

template<typename U, typename...Args>
void f(U const& u, Args&... args){
std::cout << "clvalue, ";
f(args...);
}

(tested using g++ 4.5.1)

Cheers!
SG
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top