如何编写一般std :: vector push_back的模板函数?

时间:2017-04-03 23:19:34

标签: c++ templates

我有两种或不同类型的std::vector

struct data{
   int a;
   int b;
   int c;
};

std::vector<int>  val1;
std::vector<data> val2;

现在我想编写一个适用于val1val2的模板函数。

template<typename t>
void my_function(t s){
    s.push_back(...); // based on s i.e it could be std::vector<int> or std::vector<data> 
}

my_function<std::vector<int>>(val1);
my_function<std::vector<data>>(val2);

我面临的问题是如何在代码中说明,如果类型为std::vector<int>,请{i} s.push_back({1})std::vector<data>执行s.push_back({1,2,3});

3 个答案:

答案 0 :(得分:3)

忘记模板。简单的重载应该可以解决您的问题:

updateQueries: Object.assign(...['New', 'Hot', 'Notification', 'Own'].map(
    key => ({ 
        [key + 'Posts']: (previousResult, { mutationResult }) => 
            deletePostUpdateQuery(previousResult, mutationResult, key.toLowerCase() + 'Posts') 
    })
));

答案 1 :(得分:1)

似乎你想专门化你的模板功能, 你可以这样做:

struct data{
   int a;
   int b;
   int c;
};

std::vector<int>  val1;
std::vector<data> val2;

template<typename t> void my_function(t s);

template<>
void my_function(std::vector<int> s){
    s.push_back({1}); 
}

template<>
void my_function(std::vector<data> s){
    s.push_back({1,2,3}); 
}

int main()
{
    my_function(val1);
    my_function(val2);
}

答案 2 :(得分:0)

不确定它是你要找的......

您可以模仿my_function() espliciting std::vector并提取以这种方式包含的类型

template <typename T>
void my_function(std::vector<T> & s)
 { s.push_back(getTval<T>()); }

(偏离主题:观察我为参数&添加了s;否则您将向量s作为副本传递,push_back()添加仅在退出函数的副本中的值)

但是这个解决方案并没有避免功能专业化的需要;它只是在getVal()

的实施中移动了这个需求
template <typename T>
T getTval ();

template <>
int getTval<int> ()
 { return 1; }

template <>
data getTval<data> ()
 { return {1, 2, 3}; }

如果my_function()是一个伟大而复杂的解决方案,push_back()是向量中包含的数据改变代码的唯一点,那么这可能很有用。否则,我认为可以更好地重载或专门化相同的my_function()

相关问题