繁体   English   中英

c ++中嵌套模板函数的const限定符

[英]const qualifier for nested template functions in c++

我想要一个模板功能来调用带有const限定符的模板函数foo

函数foobar有两个模板及其实例化。 这是foo.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*);

foo.h

template <class T>
void foo(T x);

bar.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*);

bar.h

template <class T>
void bar(T x);

最后, main.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应该得到一个int数组,而不是改变它,因此它有const限定符。 我希望函数接收一个int数组并更改它,而在某些时候它也应该调用函数foo 模板使用的原因是,将来我想为不同类型的数据调用这些函数,例如double *std :: vector <int>&等。

当我尝试编译时,我收到以下错误:

undefined reference to `void foo<int* const>(int* const)'

好像它不能将int *转换const int * 此外,它似乎将指向const int的指针替换为指向int的const指针。 知道我怎么处理它吗?

还有一个观察结果:如果我删除foo.cppbar.cpp ,而是将所有内容合并到一个文件中,它会正常编译。

===================================

案件解决了

foo的实例化是为<const int *>完成的 正如人们注意到的那样,当foobar中调用时, const T会转换为T const == int * const ,它与const int *不同

为了把它变成int const * ,我添加了代码:

typedef typename std::remove_pointer<T>::type tmp_type; // tmp_type = int
foo<tmp_type const *>(x);

你需要-std = c ++ 11来编译它。 或者,正如戴维斯赫林提出的那样,你可以使用

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 *

如果Tint* ,则const Tint *const ,而不是const int* (毕竟,给定

typedef const T cT;
cT t1=/*…*/,t2=/*…*/;

这是禁止的t1=t2 ,而不是*t1=*t2 。)

您可以使用const std::remove_pointer_t<T>* const int*int*构造const int* int*

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM