c++ - 不同的值取决于 C++ 类型

标签 c++ generic-programming

我想根据输入变量的类型有不同的变量值。 代码:

template <typename T>
int getValue(vector<T> & data)
{
    return something; // There should be 0 for int and 1 for double
}

谁知道如何实现这样的功能?

最佳答案

如果您只是处理 intdouble,那么您可以为不同类型的 vector 重载函数。

int getValue(vector<int> & data)
{
    return 0;
}

int getValue(vector<double> & data)
{
    return 1;
}

如果您想将 getValue 保留为模板函数并专用于 intdouble 那么您可以使用

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;
}

Live Example

关于c++ - 不同的值取决于 C++ 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33081442/

相关文章:

scala - 在Scala中移置任意collection-of-collection

java - 以通用方式根据值返回对象

rust - 仅当满足类型约束条件时才有条件地实现 Rust 特性

c++ - 如何从 C++ 调用 QML 对象的方法

c# - 如何使用 C++ 静态库编译 C# 应用程序?

c++ - 这是将位写入大端的正确方法吗?

c++ - C++-从派生类中提取模板参数

python - 在 python 中通过引用传递引用

c++ - 是否可以将 Debug模式编译的库链接到 Release模式的项目?

java - 通用对类