gpt4 book ai didi

c++ - 具体语法问题

转载 作者:行者123 更新时间:2023-11-28 08:24:06 25 4
gpt4 key购买 nike


是否可以为初始化创建模板,例如:

template <typename C> typename C::value_type  fooFunction(C& c) {...};
std::vector<string> vec_instance;
fooFunction(cont<0>(vec_instance));
fooFunction(cont<1>(vec_instance));

总的来说,我感兴趣的是是否可以使用整数(即 0)而不是真实类型名称来指定模板。又是如何实现的呢?

最佳答案

我不是很清楚你在问什么,但下面的代码片段对我有用:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

template <typename C>
typename C::value_type fooFunction(const C & c) { return 0; };
/* note that fooFunction takes a ref-to-const, not a reference */

template<int N>
struct cont
{
public:
typedef int value_type;
cont(vector<string> vec) {};
};

int main()
{
std::vector<string> vec_instance;
fooFunction(cont<0>(vec_instance));
fooFunction(cont<1>(vec_instance));
}

两个值得注意的变化:

  1. 整数不是类型,所以如果声明了 cont template <typename T> ,你写的是行不通的。 template <int N>是对整数值进行参数化的正确方法,如 templatetypedef 所述。

  2. 我不确定如何cont<>已定义,但根据您的使用情况,它必须是您正在构建的临时对象。您将无法将此临时文件作为引用传递给 fooFunction .请注意,我上面的示例将 C 作为对常量的引用传递。

关于c++ - 具体语法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4663395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com