I would like to re-declare the type of a given variable, but unfortunately reinterpret_cast<> does not help here. This line:
reinterpret_cast<std::vector<double>>(std::string("Hello"));
results in the following compiler error:
invalid cast from type 'std::string {aka std::basic_string<char>}' to type 'std::vector<double>'
Is there a different, clean approach?
Notes:
Edit/Some context: This line will be part of a templated function, with:
reinterpret_cast<T>(std::string())
For T == std::string this is completely fine, but unfortunately the compiler will also try to instantiate (but at runtime never use) it for T == std::vector<>. And this is C++11, so there is no static_if.
For T == std::string this is completely fine, but unfortunately the compiler will also try to instantiate (but at runtime never use) it for T == std::vector<>. And this is C++11, so there is no static_if.
In C++17, as you said, you can use if constexpr
:
template <typename T>
void foo(const T& value)
{
bar(value);
if constexpr (std::is_same<std::string, T>::value) {
// Specific code for string
} else constexpr (std::is_same<std::vector<int>, T>::value) {
// specific code for vector...
}
// ...
}
Prior to C++17, you might use overloads, potentially with tag dispatching, SFINAE.
void foo_specific(const std::string& s)
{
// Specific code for string
}
void foo_specific(const std::vector<T>& v)
{
// Specific code for vector
}
template <typename T, std::enable_if_t<std::is_integral<T>::value>, int> = 0>
void foo_specific(const T& n)
{
// Specific code for integral
}
// ...
template <typename T>
void foo(const T& value)
{
bar(value);
foo_specific(value);
// ...
}