I'd like to write a type alias template that resolves to the const of the template parameter for most types, like so:
template <typename T>
using TypeAlias = const T;
but for a particular type, say int, it simply resolves to T.
I've tried doing this with std::conditional, as well as specialization of structs containing the type alias, but in all cases, the compiler is unable to infer the type. My questions are: what am I doing wrong in the examples below? and How does one do this correctly?
Edit: I'm working in a very large codebase that handles a large number of types, and adds const to all of them in the definition of TypeAlias (which is actually a more complicated type, basically a container templated over const T). I'm trying to modify this codebase to accept a new type which cannot be const, while making minimal modifications. Explicitly specifying the type in all templated functions like foo isn't a workable solution. What I'm really looking for is a way to modify TypeAlias, and little to nothing else.
example 1:
#include <stdio.h>
#include <type_traits>
template <typename T>
using TypeAlias = typename std::conditional<std::is_same<int, T>::value,
T, typename std::add_const<T>::type>::type;
template <typename T>
void foo(TypeAlias<T> var) {
printf("var = %f\n", static_cast<double>(var));
}
int main(int argc, char *argv[]) {
const int a = 1;
const float b = 2;
const double c = 3;
foo(a);
foo(b);
foo(c);
return 0;
}
example 2:
template <typename T>
struct TypeHolder {
using type = const T;
};
template <>
struct TypeHolder<int> {
using type = int;
};
template <typename T>
void foo(typename TypeHolder<T>::type var) {
printf("var = %f\n", static_cast<double>(var));
}
int main(int argc, char *argv[]) {
int a = 1;
const float b = 2;
const double c = 3;
foo(a);
foo(b);
foo(c);
return 0;
}