Is it possible to "pass" an unnamed parameter without creating a temporary variable?

I wrote a simple type-based dispatcher using an unnamed parameter, which I assume is pretty normal.

When it came to calling the function, I wanted to get the overload without having any variable. Is it possible?

eg.

void f1(int /*can change the type*/) {
}
int main(int, char*) {
  f1(/*what to put here?*/); 
  return 0;
}

My “real” example was a simple type-based dispatcher. The best I came up with was a pointer as an unnamed parameter, I think it has the least overhead:

#include <iostream>
using namespace std;

template<typename U>
class A {
public:

A(const U& u) : u(u) {};

template <typename T>
T get_as() {
    T* t; // <- ugly
    return get(t);
}

U get(U*) {
    return u;   
}

int get(int*) {
    return i;
}

double get(double*) {
    return d;
}

private:
    U u;
    int i = 5;
    double d = 3.14;
};

int main() {
    A<string> a("name");
    cout << a.get_as<double>() << '\n';
    cout << a.get_as<int>() << '\n';
    cout << a.get_as<string>() << '\n';
    return 0;
}

I assume this is purely aesthetically pleasing with a pointer, because it is probably optimized, but still I am interested. I also suggest that this may not be possible because (AFAIK) this argument goes through the stack. So technically there is always “overhead”. Is it correct?

, , " " ?

PS. , T*(0) "" , , , .

+4
2

, :

template<class T> struct tag {};

double get(tag<double>) {
    return d;
}

template <typename T>
T get_as() {
    return get(tag<T>{});
}

, .

(: AB64 AMD64?, .)

+6

"", , :

Live Demo

template<typename U>
class A
{
public:
    static_assert(!std::is_same<int, U>::value && !std::is_same<double,U>::value,
                               "Template argument cannot be <int> or <double>.");
    A(const U& u) : u(u) {};
    explicit operator U() { return u; }
    explicit operator int() { return i; }
    explicit operator double() { return d; }

private:
    U u;
    int i = 5;
    double d = 3.14;
};

int main()
{
    A<string> a("wow");
    cout << double(a) << '\n';
    cout << int(a) << '\n';
    cout << string(a) << '\n';
    return 0;
}

, , .

. , .

+1

All Articles