Template funkcji

0

Cześć, mam problem z templatami. Muszę zrobić funkcję która zwróci wartość w typie zależnym od zmiennej której ma być przypisanej. Czy jest do w ogóle możliwe? Wydaje mi się że gdzieś coś takiego widziałem. Typ musi sam się wycastować, tzn. nie ma to być zwykły template typu Funkcja<double>();
<code=cpp
template <class Typ>
Typ Funkcja()
{
return Typ(1000);
}

int main()
{
double Wartosc1 = Funkcja();
float Wartosc2 = Funkcja();
int Wartosc3 = Funkcja();

return 0;

}

0

Nie wiem czemu popsuło mi formatowanie :/

template <class Typ>
Typ Funkcja()
{
    return Typ(1000);
}

int main()
{
    double Wartosc1 = Funkcja();
    float Wartosc2 = Funkcja();
    int Wartosc3 = Funkcja();

    return 0;
}
4

Do dyspozycji masz http://en.cppreference.com/w/cpp/language/template_argument_deduction
Kompilator może domyślić się wyłącznie typu parametrów.

#include <iostream>
using namespace std;

template<typename T>
void clean(T &val) {
	val = T{};
}

int main() {
	int a = 123;
	double b = 0.13;
	
	clean(a);
	clean(b);
	
	cout << a << " " << b << endl;
	return 0;
}

http://ideone.com/CcVxPx

C++ doesn't do type inference on the return value. I.e., the fact that it is being assigned to an int isn't used in template parameter deduction.

1 użytkowników online, w tym zalogowanych: 0, gości: 1