Reputation: 2830
When a pointer type is passed as argument to template parameter T, how do I declare a pointer to const type? Both const T and T const become const pointer to type, whereas I need to declare a pointer to const type.
template<typename ValueType>
class TestClass {
public:
void TestMethod(const ValueType x) {
// When ValueType is int*,
// type of x is int * const;
// how do I declare x such that it is const int* ?
std::cout<<x;
}
};
Upvotes: 2
Views: 356
Reputation: 63152
You can create a trait that does it.
template <typename T>
struct add_inner_const { using type = const T; };
template <typename T>
struct add_inner_const<T*> { using type = const T*; };
template <typename T>
using add_inner_const_t = typename add_inner_const<T>::type;
template<typename ValueType>
class TestClass {
public:
void TestMethod(add_inner_const_t<ValueType> x) {
// When ValueType is int*, x is const int*
std::cout<<x;
}
};
This will transform int **
into int * const *
, if you instead want that to be const int **
, then you need a different specialisation
template <typename T>
struct add_inner_const<T*> { using type = add_inner_const_t<T>*; };
Upvotes: 2