提问者:小点点

C++中嵌套模板函数的常量限定符


我想要一个模板函数条调用一个模板函数foo与常量限定符。

我有两个函数的模板foo和bar及其实例化。这是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*转换为常量int*。而且,它似乎将指向const int的指针替换为指向int的const指针。知道我该怎么处理吗?

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

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

破案

foo的实例化是为(<)完成的;常量信息*&>。正如人们所注意到的,当在bar中调用foo时,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来编译它。或者,正如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*。


共1个答案

匿名用户

如果,则,而不是。(毕竟,给定

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

禁止的是,而不是

您可以使用构造

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|中|嵌套|模板|函数|常量|限定符)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?