miq*_*elm 3 c++ generic-programming
我想根据输入变量的类型有不同的变量值.码:
template <typename T>
int getValue(vector<T> & data)
{
return something; // There should be 0 for int and 1 for double
}
Run Code Online (Sandbox Code Playgroud)
有谁知道如何实现这样的功能?
如果你只是处理一个int,并double那么你可以只重载函数的不同的充类型的载体.
int getValue(vector<int> & data)
{
return 0;
}
int getValue(vector<double> & data)
{
return 1;
}
Run Code Online (Sandbox Code Playgroud)
如果你想保持getValue作为模板功能,专门为int和double那么你可以使用
template<typename T>
int getValue(std::vector<T> & data)
{
return -1;
}
template <>
int getValue(std::vector<int> & data)
{
return 0;
}
template <>
int getValue(std::vector<double> & data)
{
return 1;
}
Run Code Online (Sandbox Code Playgroud)