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

标签 c++ templates constants

我想要一个模板函数 bar 来调用带有 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 限定符。我希望函数 bar 接收一个 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 的实例化是为 完成的。正如人们注意到的那样,当 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 来编译它。或者,正如 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*

最佳答案

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

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

t1=t2那是被禁止的,不是*t1=*t2 .)

您可以使用 const std::remove_pointer_t<T>* build const int*来自 int* .

关于c++ - C++ 中嵌套模板函数的 const 限定符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56589744/

相关文章:

c++ - 在 CMake 中使用 protobuf 作为 ExternalProject

c++ - 在编译时区分char和wchar_t

c++ - 指向指针(二维数组)的指针作为输入参数

c++ - const 参数传递 : invalid conversion

c++ - gcc 发出的这个越界警告是错误的吗?

c++ - std::atomic_...<std::shared_ptr> 应该如何用于线程安全类的复制和移动操作?

c++ - 带有 C++ 解决方案的 C 库

具有不同值类型模板参数的模板类的 C++ 数组或 vector

c++ - 独立源文件中的 SFINAE 模板特化

c++ - 函数返回中const T&和T的区别