C++ 中嵌套模板函数的常量限定符
const qualifier for nested template functions in c++
我想要一个模板函数栏来调用带有常量限定符的模板函数foo。
我有两个函数foo和bar的模板及其实例化。这是福.cpp
#include "foo.h"
#include <iostream>
template <class T>
void foo(const T x){
std::cout<<x[0]<<std::endl;
};
// instantiation here, in order to avoid implementation in header
template void foo<const int*>(const int*);
傅炯:
template <class T>
void foo(T x);
酒吧.cpp:
#include "bar.h"
#include "foo.h"
#include <iostream>
template <class T>
void bar(T x){
foo<const T>(x);
};
// instantiation here, in order to avoid implementation in header
template void bar<int*>(int*);
和酒吧:
template <class T>
void bar(T x);
最后,主要.cpp:
#include <iostream>
#include "bar.h"
#include "foo.h"
int main()
{
int p[5];
p[0]=17;
foo(p);
bar(p);
return 0;
}
所有.h文件都包含 #ifndef/#define 标准语句。函数foo应该得到一个ints数组,而不是改变它,因此它有const限定符。我希望函数栏接收一个ints 数组并更改它,而在某些时候它也应该调用函数foo。使用模板的原因是,将来我想为不同类型的数据调用这些函数,例如double*,std::vector
当我尝试编译时,出现以下错误:
undefined reference to `void foo<int* const>(int* const)'
好像它不能将int* 转换为const int*。此外,它似乎将指向 const int 的指针替换为指向 int 的 const 指针。知道我该如何处理吗?
还有一个观察:如果我删除foo.cpp和bar.cpp而是将所有内容合并到一个文件中,它会正常编译。
====
==================================案例已解决
foo的实例化是为
为了将其转换为int const*,我在代码中添加了:
typedef typename std::remove_pointer<T>::type tmp_type; // tmp_type = int
foo<tmp_type const *>(x);
你需要 -std=c++11 来编译它。或者,正如戴维斯·赫林(Davis Herring)所建议的那样,您可以使用
foo<const std::remove_pointer_t<T>*>(x);
相反,但您需要为此使用 -std=c++14。
该问题与头文件中模板的实现无关,除了明显的观察结果,即如果所有内容都在一个文件中,则不需要这些。
另一种解决方案是为 foo 设置两个实例化:
template void foo<int const *>(int const *);
template void foo<int *>(int *);
其中第一个不允许你在函数内更改指针的值,而第二个允许你只在其中传递简单的int*。
如果T
是int*
,const T
是int *const
,而不是const int*
。 (毕竟,鉴于
typedef const T cT;
cT t1=/*…*/,t2=/*…*/;
禁止的是t1=t2
,而不是*t1=*t2
。
您可以使用const std::remove_pointer_t<T>*
从int*
构造const int*
。
- 常量函数,当其参数是对文字类型的引用时
- 为什么在C++使用常量函数时常量是多余的?
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- 为什么在PIMPL中无法访问实现类的常量函数?
- 常量函数参数的专业化
- 如何调用非常量函数而不是常量函数?
- 常量和非常量函数作为模板参数参数
- 通过引用常量函数调用另一个类的非常量函数
- C++编译器如何检测非常量函数体
- 使用常量函数返回常量引用时出现奇怪的行为
- 常量字符数组模板与字符常量* 函数重载
- 现代C++编译器是否能够避免在某些条件下两次调用常量函数
- 将函数声明为 GCC 纯函数或常量函数的效果(当它不是时)
- 为什么常量/非常量函数重载的继承不明确
- 类型定义模板,接受指向常量和非常量函数的指针
- 如何避免语法相同的常量和非常量函数之间代码重复,这些函数在语义上不相同
- 继承的常量函数
- 不确定 c++ 中的常量函数是什么
- 在常量函数中使用安全的非常量函数
- c++如何定义其他开发人员需要调用的常量函数顺序