【问题标题】:Pass template parameter to function which calls member functions将模板参数传递给调用成员函数的函数
【发布时间】:2015-02-10 05:49:25
【问题描述】:

我想将仅在编译期间已知的类型的向量传递给一个函数,该函数将其传递给其他函数(根据向量的类型推送元素)。

应该怎么做才能保证编译器不抛出错误:

test.cpp:在 'void funcPushInt(std::vector) [with C = classB]' 的实例化中: test.cpp:28:20:'void checkType(std::vector) [with A = classB]'需要 test.cpp:53:16:从这里需要 test.cpp:38:3: 错误: 没有匹配函数调用'std::vector::push_back(int&)' vec.push_back(i); ^

#include <typeinfo>
#include <vector>
using namespace std;

class classB
{
    private:
        int i;
    public:
        B()
        {
            i = 0;
        }
}

template <class A>
void checkType(vector<A>);
template <class C>
void funcPushInt(vector<C>);
template <class B>
void funcPushClassB(vector<B>);

template <class A>
void checkType(vector<A> vec)
{
  // check type of vec
  if(typeid(vec) == typeid(vector<int>)) 
    funcPushInt(vec);
  else if(typeid(vec) == typeid(vector<classB>))
    funcPushClassB(vec);
}

template <class C>
void funcPushInt(vector<C> vec)
{
  // push int
  int i = 1;
  vec.push_back(i);
}

template <class B>
void funcPushClassB(vector<B> vec)
{
  // error as it can't push float to vector<int>
  classB objB;
  vec.push_back(objB);
}

int main()
{
    // empty vec of classB type
  vector<classB> vec;
  checkType(vec);
}

【问题讨论】:

  • 我更关心所有没有声明返回类型和按值参数的模板函数,在这些函数上,本地更改在返回时对调用者没有任何意义
  • 经典 XY 问题。顺便说一句,使用value_type
  • 你真正想做什么?
  • 基本上:1)检查向量的类型 2)根据类型,创建该类型的对象并将其推入
  • 如何创建对象?您是否假设它是默认可构造的?

标签: c++ templates


【解决方案1】:

您的函数没有返回类型。假设这是一个遗漏的错误,你还不如有两个功能。

template <class A>
void checkType(vector<A> vec)
{
    funcPushFloat(vec);
}

void checkType(vector<int> vec)
{
    funcPushInt(vec);
}

【讨论】:

  • 谢谢或回复,但我想要一个 checkType 函数而不是使用多个函数。是的,我忽略了返回类型
  • 你想要一个函数有技术原因吗?
  • 不是真的.. 只是为了方便起见,不必重复一堆代码。我想我必须那样做。谢谢 R 萨胡!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-23
  • 2020-04-29
  • 2020-10-26
相关资源
最近更新 更多