如果我有一个接受模板类型指针的模板函数:
template<typename T>
void foo(const T* x);
它自然接受指向非常量对象的指针:
int* x = ...;
foo(x); //int* implicitly converted to const int *
我想对具有指针语义的模板类执行相同的操作。
例如最近提出的array_view类是连续内存块的 View ,具有(非拥有)指针语义,可用于引用可变或常量项的数组:
array_view<int> av = ...;
av[0] = 1;
array_view<const int> cav = ...;
cav[0] = 1; // <- error: read-only variable is not assignable
问题是上面带有原始指针的模式不起作用:
template<typename T>
void foo(array_view<const T> x);
...
array_view<int> x;
foo(x); // <- error: no matching function for call to 'foo'
即使我添加了在 T
之间进行转换的复制构造函数或转换运算符和 const T
编译器无法解析 T
的变体用于模板。
我知道 2 个解决方法:
- 在调用时明确指定模板参数:
foo<int>(x)
- 写一个更通用的模板:
template<typename U> void foo(U x)
也许约束U
元编程。
有没有更好的解决方案?
最佳答案
显而易见的解决方案是使用
template <typename T>
void foo(std::array_view<T> x);
有趣的是,这适用于两种形式的数组 View :
int array[] = { 1, 2, 3 };
foo(array_view<int>(std::begin(array), std::end(array)));
foo(array_view<int const>(std::begin(array), std::end(array)));
const
参数的 -ness 由 const
隐式强制执行-论证的性质。顺便说一句,如果推导指针对象类型,指针参数也是如此:
template <typename T>
void bar(T*);
当 bar()
用 int const*
调用类型 T
推导为 T const
.主要需要const
version 是已经推导出类型但参数应该适合的时候。但是,在那种情况下 std::array_view<...>
转换同样有效。
关于c++ - 原始指针隐式转换为常量指针,需要与用户类型相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32364932/